R:根据特定条件聚合数据帧 [英] R: aggregate a data frame based on certain condition
本文介绍了R:根据特定条件聚合数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df< -data.frame(X = c(a ,b,c,d),Y = c(0.5,0.4,0.01,0.09))
XY
a 0.5
b 0.4
c 0.01
d 0.09
l <-c(a,c,d)
l是需要分组在一起的列表。所以,这里我想把所有的元素分组到l中的 df $ X
中。
我想要的结果是:
XY
a'0.6
b 0.4
任何想法如何做到这一点?
谢谢。
解决方案
我们可以暂时将相关的 X
相同的分组变量然后聚合。这里我随意选择 l [1]
,这也恰好是a
#XY
#1 a 0.6
#2 b 0.4
aggregate()调用中,使用在()
之前的一个方面是原始的 df
将保持不变。
I have a data frame. I want to aggregate one column of it based on another list.
df<-data.frame(X=c("a", "b", "c", "d"), Y=c(0.5, 0.4, 0.01, 0.09))
X Y
a 0.5
b 0.4
c 0.01
d 0.09
l<-c("a", "c", "d")
l is the list which needs to grouped together. So, here I want to group all the elements in df$X
that are there in l.
My desired result is:
X Y
a' 0.6
b 0.4
Any idea on how to do this?
Thanks.
解决方案
We can "temporarily" change the relevant X
values to the same grouping variable and then aggregate. Here I arbitrarily choose l[1]
, which also happens to be "a"
aggregate(Y ~ X, within(df, X <- replace(X, X %in% l, l[1])), sum)
# X Y
# 1 a 0.6
# 2 b 0.4
One upside to this use of within()
in the aggregate()
call is that the original df
will remain unchanged.
这篇关于R:根据特定条件聚合数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文