如何从数组R中的特定数字开始?

时间:2019-01-25 15:51:49

标签: r

如果我有这个数组:

   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

1 个答案:

答案 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))