我有一个数据框,其格式非常类似于下面给出的示例数据框 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)
答案 0 :(得分:6)
如果您想考虑其他软件包,可以尝试使用我的“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