根据R中的条件计算平均值 [英] Calculating average Based on Condition in R
本文介绍了根据R中的条件计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请参阅问题计算基于条件 ,我需要根据列<$ c来计算列 E
的平均值
$ c> F
Referring to the question "Calculating average of based on condition", I need to calculate average
of the column E
based on the column F
下面是我的数据框 df
的一部分,但我的实际数据为65K值。
Below is my part of data frame df
but my actual data is 65K values.
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
基于提到的帖子中提供的解决方案,以下是我的脚本。
Based on the solution provided in the mentioned post, below is my script.
setDT(df)[, Avg := c(rep(mean(head(d$fE, 5)), 5), rep(0, .N-5)),
cumsum(c(TRUE, diff(abs(F)!=1)==1))]
但是执行时出现以下错误。
But when executed I am getting the below error.
rep(0,.N-5)中的错误:无效的'times'参数
Error in rep(0, .N - 5) : invalid 'times' argument
推荐答案
使用合计:
agg <- aggregate(df$E,by=list(df$F), FUN=mean)
您使用了一个数据表示例,但您说的是qu
数据表中的数据框:
you used a data table example, but you said data frame in your qu data table:
# 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)]
这篇关于根据R中的条件计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文