[英]How do I aggregate data in a R dataframe
I have a dataframe that looks like我有一个 dataframe 看起来像
Col A | Col B | Col C
1 2 3
2 4 5
3 1 3
4 2 3
and I want to mutate my dataframe to aggregate Col B and Col C based on groups in col A. The col A groups are <= 2 and >2.我想改变我的 dataframe 以基于 col A 中的组聚合 Col B 和 Col C。col A 组是 <= 2 和 >2。
Col A | Col B | Col C
<=2 6 8
>2 3 6
How would I go about doing this?我将如何 go 这样做?
You can try aggregate
+ ifelse
like below您可以尝试
aggregate
+ ifelse
,如下所示
aggregate(
. ~ ColA,
transform(
df,
ColA = ifelse(ColA <= 2, "<=2", ">2")
), sum
)
which gives这使
ColA ColB ColC
1 <=2 6 8
2 >2 3 6
A data.table
option data.table
选项
> setDT(df)[, lapply(.SD, sum), .(ColA = ifelse(ColA <= 2, "<=2", ">2"))]
ColA ColB ColC
1: <=2 6 8
2: >2 3 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.