我有类似 (a,b,c) 的数据
a b c
1 2 1
2 3 1
9 2 2
1 6 2
其中“a”范围被分为 n(比如 3)个相等的部分,聚合函数计算 b 值(比如最大值)并按“c”分组。
所以输出看起来像
a_bin b_m(c=1) b_m(c=2)
1-3 3 6
4-6 NaN NaN
7-9 NaN 2
这是MxN,其中M=a的数量,N=唯一的c个样本或所有范围
我该如何处理这个问题?有 R 包可以帮助我吗?
最佳答案
聚合
、剪切
和 reshape
的组合似乎有效
df <- data.frame(a = c(1,2,9,1),
b = c(2,3,2,6),
c = c(1,1,2,2))
breaks <- c(0, 3, 6, 9)
# Aggregate data
ag <- aggregate(df$b, FUN=max,
by=list(a=cut(df$a, breaks, include.lowest=T), c=df$c))
# Reshape data
res <- reshape(ag, idvar="a", timevar="c", direction="wide")
关于r - R 中的分组和聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350113/