做的最好的事情是創建分組變量和骨料,即
n = 4
l1 <- nrow(df) %/% n
df$grp <- c(rep(seq(l1), each = n), rep(tail(seq(l1), 1), nrow(df) - n * l1))
aggregate(L1 ~ grp, df, mean)
# grp L1
#1 1 0.9075
#2 2 1.0760
DATA
dput(df)
structure(list(Year = 1960:1968, L1 = c(1.11, 1.14, 0.75, 0.63,
1.15, 1.08, 1.69, 0.77, 0.69)), .Names = c("Year", "L1"), row.names = c(NA,
-9L), class = "data.frame")
編輯
基於您的評論(我有一些時間來殺死),這裏是接受type
參數指定分組方法的功能,
f1 <- function(df, n, type = 1){
if(type == 1){
l1 <- nrow(df) %/% n
df$grp <- c(rep(seq(l1), each = n), rep(tail(seq(l1), 1), nrow(df) - n * l1))
return(aggregate(L1 ~ grp, df, mean))
} else {
if(type == 2){
l1 <- nrow(df) %/% n
df$grp <- c(rep(seq(l1), each = n), rep(tail(l1, 1)+1, nrow(df) - n * l1))
return(aggregate(L1 ~ grp, df, mean))
}
}
}
f1(df, 4, type = 1)
# grp L1
#1 1 0.9075
#2 2 1.0760
f1(df, 4, type = 2)
# grp L1
#1 1 0.9075
#2 2 1.1725
#3 3 0.6900
您使用colMeans,因爲它可以更容易地創建一個分組變量,然後使用聚合 – user20650