通过固定长度的组获取数据帧的平均值

时间:2014-12-04 14:52:15

标签: r dataframe

我有一个带

的数据框
V1     V2 
1      9
1.1    10 
1      10.5
2.01   15
2      14
...

我想得到每组3的手段(跳跃,不滚动),所以结果应该是:

V1     V2 
1.xx   10.xx
2.xx   15.xx
...

我挖掘了applyrapplyaggregate,但无法找到如何做到这一点......

1 个答案:

答案 0 :(得分:3)

尝试

df$gr <- as.character(gl(nrow(df),3, nrow(df)))
library(dplyr)
df %>%
   group_by(gr) %>%
   summarise_each(funs(mean=mean(., na.rm=TRUE)))

#    gr       V1        V2
#1  1 1.033333  9.833333
#2  2 2.005000 14.500000

data.table

library(data.table)
setDT(df)[, lapply(.SD, mean), by=gr]
#   gr       V1        V2
#1:  1 1.033333  9.833333
#2:  2 2.005000 14.500000

或使用aggregate

中的base R
aggregate(.~gr, df, mean)
#    gr       V1        V2
#1  1 1.033333  9.833333
#2  2 2.005000 14.500000

基于sapply的方法,不使用gr

t(sapply(seq(1, nrow(df), by=3), function(i){
                   indx <- i:(i+2)
           colMeans(df[indx[indx <=nrow(df)],])}))
 #           V1        V2
 #[1,] 1.033333  9.833333
 #[2,] 2.005000 14.500000

数据

df <- structure(list(V1 = c(1, 1.1, 1, 2.01, 2), V2 = c(9, 10, 10.5, 
15, 14)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, 
-5L))