计算每组的行数并将结果添加到原始数据帧 [英] Count number of rows per group and add result to original data frame
本文介绍了计算每组的行数并将结果添加到原始数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个 data.frame
对象:
df <- data.frame(name=c('black','black','black','red','red'),
type=c('chair','chair','sofa','sofa','plate'),
num=c(4,5,12,4,3))
现在,我想计算名称
和类型的每种组合的行数(观察数)
。可以这样完成:
Now I want to count the number of rows (observations) of for each combination of name
and type
. This can be done like so:
table(df[ , c("name","type")])
,或者也可以与 plyr
,(尽管我是不确定如何)。
or possibly also with plyr
, (though I am not sure how).
但是,如何将结果合并到原始数据框中?这样结果将如下所示:
However, how do I get the results incorporated into the original data frame? So that the results will look like this:
df
# name type num count
# 1 black chair 4 2
# 2 black chair 5 2
# 3 black sofa 12 1
# 4 red sofa 4 1
# 5 red plate 3 1
其中 count
现在存储聚合结果。
where count
now stores the results from the aggregation.
使用 plyr
的解决方案也可能很有趣,尽管我想看看如何用基数R完成此操作。 / p>
A solution with plyr
could be interesting to learn as well, though I would like to see how this is done with base R.
推荐答案
另一种概括更多的方法:
Another way that generalizes more:
df$count <- unsplit(lapply(split(df, df[c("name","type")]), nrow), df[c("name","type")])
这篇关于计算每组的行数并将结果添加到原始数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文