参考问题“根据条件计算平均值” https://stackoverflow.com/questions/45206230/calculating-average-of-based-on-condition/45206365?noredirect=1#comment78219079_45206365,我需要计算average
列的E
基于列F
下面是我的数据框的一部分df
但我的实际数据是 65K 值。
E F
3.130658445 -1
4.175605237 -1
4.949554963 0
4.653496112 0
4.382672845 0
3.870951272 0
3.905365677 0
3.795199341 0
3.374740696 0
3.104690415 0
2.801178871 0
2.487881321 0
2.449349554 0
2.405409636 0
2.090901539 0
1.632416356 0
1.700583696 0
1.846504012 0
1.949797831 0
1.963114449 0
2.033100326 0
2.014312751 0
1.997178247 0
2.143775497 0
根据上述帖子中提供的解决方案,下面是我的脚本。
setDT(df)[, Avg := c(rep(mean(head(d$fE, 5)), 5), rep(0, .N-5)),
cumsum(c(TRUE, diff(abs(F)!=1)==1))]
但是执行时我收到以下错误。
rep(0, .N - 5) 中的错误:“times”参数无效
使用聚合:
agg <- aggregate(df$E,by=list(df$F), FUN=mean)
您使用了数据表示例,但您在 qu 中提到了数据框
数据表:
# this will retain all rows and return mean as a new column (per group_
df[, Mean:=mean(E), by=list(F)]
# this will return means per group only
df[, mean(E),by=.(F)]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)