This question already has answers here:
Repeat each row of data.frame the number of times specified in a column

(8个答案)


2年前关闭。





我有一个数据帧,其格式非常类似于下面给出的示例数据帧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 - 整洁的数据:根据“计数”变量为每个人创建一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29728086/

10-12 22:38
查看更多