Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对R中的列数据求一系列值的平均值_R - Fatal编程技术网

对R中的列数据求一系列值的平均值

对R中的列数据求一系列值的平均值,r,R,我的数据集(testdata)的排列如下: Time 1 2 3 1 0 569.607 557.689 527.353 2 1 569.208 556.697 527.162 3 2 569.278 556.919 528.125 4 3 570.059 555.621 527.158 我需要找到第1列、第2列和第3列在

我的数据集(testdata)的排列如下:

           Time    1       2        3
1           0   569.607  557.689   527.353
2           1   569.208  556.697   527.162
3           2   569.278  556.919   528.125
4           3   570.059  555.621   527.158
我需要找到第1列、第2列和第3列在特定时间范围内的平均值,并将其制成表格。例如,我需要列1的平均值,其中时间是20-30,然后是40-50,然后是60-70

为了找到20:30的平均值,我使用了:

 sapply(testdata[testdata$Time %in% c(20:30), ],mean)
导致

Time     1        2         3 
25.5000 570.5897 557.3413 528.5433

这对于一个时间范围来说是可以的,但我想一次计算几个时间范围——有没有办法做到这一点?谢谢

如果df是您的数据帧,您可以尝试以下操作:

ranges <- list(20:30, 40:50, 60:70)
t(sapply(ranges, function(x) sapply(df[df$Time %in% x,], mean)))

范围如果df是您的数据帧,您可以尝试以下操作:

ranges <- list(20:30, 40:50, 60:70)
t(sapply(ranges, function(x) sapply(df[df$Time %in% x,], mean)))

范围您可以将其映射到函数:

h <- function(x,y){
sapply(testdata[testdata$Time %in% c(x:y), ],mean)

h您可以将其映射到函数:

h <- function(x,y){
sapply(testdata[testdata$Time %in% c(x:y), ],mean)

h如果您在rSee
?cut
?aggregate
中使用dput函数共享您的样本数据,那么提供完整的答案将更容易——类似于
聚合(.~cut(Time,c(0,20,30,40)),testdata,mean)
如果您在rSee
?cut
?aggregate
中使用dput函数共享您的样本数据,那么提供完整的答案将更容易——类似于
聚合(.~cut(Time,c(0,20,30,40)),测试数据,平均值)