这是一种没有循环的方法。
- 矩阵转换为数组。
- 数组转置为
aperm() 以允许...
-
colMeans() 返回预期的输出。 colMeans() 处理维度的方式与 rowMeans() 不同,转置提供了预期的输出。
df<-matrix(1:30, nrow = 3, ncol = 6)
ncols <- 2
colMeans(
aperm(
array(df, dim = c(3, ncols, ncol(df) / ncols)),
perm = c(2,1,3)
)
)
#> [,1] [,2] [,3]
#> [1,] 2.5 8.5 14.5
#> [2,] 3.5 9.5 15.5
#> [3,] 4.5 10.5 16.5
由reprex package (v0.3.0) 于 2019 年 9 月 30 日创建
这是三种方法中最快的:
# A tibble: 3 x 13
expression min median `itr/sec` mem_alloc
<bch:expr> <bch:> <bch:> <dbl> <bch:byt>
1 aperm_method 33.4us 35.1us 27291. 0B
2 rowsum_method 55.6us 57.8us 16854. 0B
3 sapply_method 93.8us 96.9us 10210. 46.5KB
原始代码:
bench::mark(
aperm_method = {
ncols <- 2
colMeans(
aperm(
array(df, dim = c(nrow(df), ncols, ncol(df) / ncols)),
perm = c(2,1,3)
)
)
}
,
rowsum_method = {
n <- 2;
t(rowsum(t(df), as.integer(gl(ncol(df), n, ncol(df))))) / n
}
,
sapply_method = {
BY = 2
sapply(1:(ncol(df)/BY), function(x) rowMeans(df[, ((x * BY) - BY + 1):(x * BY)]))
}
,
check = F #all the same except rowsum_method has colnames
)