R、 通过根据另一个向量计算值来重新组织向量

R、 通过根据另一个向量计算值来重新组织向量,r,vector,reorganize,R,Vector,Reorganize,我有两个向量: a <- c(6,5,3,1,6,7,4,5,3,2) b <- c(2,1,1,2,3,2,1,3,3,2) 更简单的例子: a <- c(1,2,3,4) b <- c(1,2,2,1) solution <- c(2.5,2.5) ab有几种方法可以实现这一点。@Ananda已经提到了一个。有些备选方案是: aggregate(a,list(b),mean) ddply(as.data.frame(a),.(b),summarize,mea

我有两个向量:

a <- c(6,5,3,1,6,7,4,5,3,2)
b <- c(2,1,1,2,3,2,1,3,3,2)
更简单的例子:

a <- c(1,2,3,4)
b <- c(1,2,2,1)
solution <- c(2.5,2.5)

a
b有几种方法可以实现这一点。@Ananda已经提到了一个。有些备选方案是:

aggregate(a,list(b),mean)
ddply(as.data.frame(a),.(b),summarize,mean=mean(a)) # require(plyr)
by(a,b,mean) # this is just a wrapper for tapply

选择取决于所需的输出格式和实际数据的输入格式(例如矢量与数据帧)

数据表
解决方案:

library(data.table)
d = data.table(a = c(6,5,3,1,6,7,4,5,3,2), b = c(2,1,1,2,3,2,1,3,3,2))

d[, mean(a), by = b][order(b)] # (or [order(b), V1] if you just want the means)
aggregate(a,list(b),mean)
ddply(as.data.frame(a),.(b),summarize,mean=mean(a)) # require(plyr)
by(a,b,mean) # this is just a wrapper for tapply
library(data.table)
d = data.table(a = c(6,5,3,1,6,7,4,5,3,2), b = c(2,1,1,2,3,2,1,3,3,2))

d[, mean(a), by = b][order(b)] # (or [order(b), V1] if you just want the means)