如果我有这个数组:
vector1 <- c(5,9,3)
vector2 <- c(10,11,12,13,14,15)
result <- array(c(vector1,vector2,vector1,vector2,vector1,vector2,vector1,vector2,vector1,vector2,vector1,vector2),dim = c(3,3,12))
str(result)
num [1:3, 1:3, 1:12] 5 9 3 10 11 12 13 14 15 5 ...
我需要从[,, 4]开始并数3,这样我就拥有了
[,,4] [,,5] [,,6] and then compute the mean for them
[,,7] [,,8] [,,9] and then compute the mean for them
[,,10] [,,11] [,,12] and then compute the mean for them
答案 0 :(得分:2)
这里是一种选择。使用沿第三维维度的索引对“结果”子集进行分组,使用由split
创建的分组变量对三维维度的序列进行gl
子集,遍历索引,根据以下内容对array
元素进行子集化通过获取相应元素的Reduce
索引sum
并除以3得到mean
s1 <- result[,, 4:12]
i1 <- seq(dim(s1)[3])
out <- lapply(split(i1, as.integer(gl(length(i1), 3, length(i1)))),
function(i) Reduce(`+`, lapply(i, function(i2) s1[,, i2]))/3)
如果我们想作为array
输出
array(unlist(out), c(3, 3, 3))
或melt
使其具有索引的“长整型”格式,然后创建变量summarise
的分组以获得mean
library(tidyverse)
library(reshape2)
melt(result[, , 4:12]) %>%
group_by(Var1, Var2, grp = ((Var3-1) %/% 3 ) + 1) %>%
summarise(value = mean(value)) %>%
split(.$grp) %>%
map(~ .x %>%
select(-grp) %>%
spread(Var2, value) %>%
tibble::column_to_rownames('Var1')) %>%
unlist %>%
array(c(3, 3, 3))