r - 基于 'count' 变量整理数据 : create row for each individual,

标签 r count dplyr tidyr

我有一个数据框,其格式非常类似于下面给出的示例数据框df1。共有三列:两个分类变量和一个“计数”列,用于指定具有该特定组合的对象的数量。

我想将此数据框移向示例数据框 df2 中所示的格式。每个对象不是“计数”列,而是简单地在单独的行上给出。

我已经尝试过 dplyrtidyr 软件包,但我还不太熟悉 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/

相关文章:

r - 根据 dplyr 中的组 var 计算时间戳之间的时间量

r - 将数据映射到数据框中的列的更好方法?

r igraph edge.lty 属性未按宣传的那样工作

mysql - 如何对一张表中的相同(参数)记录进行求和和分组 MySQL

mysql查询按字母顺序对同一列表中计数> 1和计数= 1的项目进行排序

php - 计算 PHP 项目中的行数

r - 相当于 purrr::map_df 中的 next

r - linux redhat gsl R安装错误: cannot run C compiled programs.

r - sparkR中collect和as.data.frame的区别

r - 根据前一组计算的另一个值传播值