根据给定列中的公共值,聚合R中相同data.frame的多行 [英] Aggregate multiple rows of the same data.frame in R based on common values in given columns
本文介绍了根据给定列中的公共值,聚合R中相同data.frame的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 data.frame
像这样:
# set example data
df <- read.table(textConnection("item\tsize\tweight\tvalue
A\t2\t3\t4
A\t2\t3\t6
B\t1\t2\t3
C\t3\t2\t1
B\t1\t2\t4
B\t1\t2\t2"), header = TRUE)
# print example data
df
item size weight value
1 A 2 3 4
2 A 2 3 6
3 B 1 2 3
4 C 3 2 1
5 B 1 2 4
6 B 1 2 2
您可以看到大小
和 weight
列不会增加任何复杂性,因为它们对于每个 item
都是相同的。但是,对于同一个项目
,可以有多个 value
。
As you can see the size
and weight
columns do not add any complexity since they are the same for each item
. However, there can be multiple value
s for the same item
.
我想使用平均值
将data.frame折叠为每个项
有一行: / p>
I want to collapse the data.frame to have one row per item
using the mean value
:
item size weight value
1 A 2 3 5
3 B 1 2 3
4 C 3 2 1
我想我必须使用聚合
函数,但是我无法弄清楚如何才能得到上述结果。
I guess I have to use the aggregate
function but I could not figure out how exactly I can get the above result.
推荐答案
aggregate(value ~ item + size + weight, FUN = mean, data=df)
item size weight value
1 B 1 2 3
2 C 3 2 1
3 A 2 3 5
这篇关于根据给定列中的公共值,聚合R中相同data.frame的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文