我有一个数据框,其格式非常类似于下面给出的示例数据框df1。共有三列:两个分类变量和一个“计数”列,用于指定具有该特定组合的对象的数量。
我想将此数据框移向示例数据框 df2 中所示的格式。每个对象不是“计数”列,而是简单地在单独的行上给出。
我已经尝试过 dplyr 和 tidyr 软件包,但我还不太熟悉 R。执行我想要的功能的好方法是什么?
set.seed(1)
x1 <- c("Pants", "Shoes", "Scarf")
x2 <- c("Ugly", "Beautiful")
x3 <- sample(1:10, size=6, replace=T)
df1 <- data.frame(Object=rep(x1, 2),
Quality=rep(x2, each=3),
Count=x3);
df1; sum(df1[,3])
df2 <- data.frame(Object=c(rep("Pants", 3), rep("Shoes", 4), rep("Scarf", 6),
rep("Pants", 10), rep("Shoes", 3), rep("Scarf", 9)),
Quality=c(rep("Ugly", 3), rep("Ugly", 4), rep("Ugly", 6),
rep("Beautiful", 10), rep("Beautiful", 3),
rep("Beautiful", 9))
)
head(df2); tail(df2)
最佳答案
如果您想考虑其他软件包,可以尝试我的“splitstackshape”软件包中的expandRows
。
用法是:
> library(splitstackshape)
> df2 <- expandRows(df1, "Count")
<小时/>
> head(df2)
Object Quality
1 Pants Ugly
1.1 Pants Ugly
1.2 Pants Ugly
2 Shoes Ugly
2.1 Shoes Ugly
2.2 Shoes Ugly
> tail(df2)
Object Quality
6.3 Scarf Beautiful
6.4 Scarf Beautiful
6.5 Scarf Beautiful
6.6 Scarf Beautiful
6.7 Scarf Beautiful
6.8 Scarf Beautiful
> nrow(expandRows(df1, "Count"))
[1] 35
关于r - 基于 'count' 变量整理数据 : create row for each individual,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29728086/