代码之家  ›  专栏  ›  技术社区  ›  John L. Godlee

列表中矩阵的滚动和

  •  1
  • John L. Godlee  · 技术社区  · 7 年前

    我有一个相同大小的矩阵列表:

    a <- matrix(data = c(1,2,3,4,5,6,7,8,9), ncol = 3, nrow = 3)
    
    b <- matrix(data = c(9,8,7,6,5,4,3,2,1), ncol = 3, nrow = 3)
    
    c <- matrix(data = c(1,2,3,4,5,6,7,8,9), ncol = 3, nrow = 3)
    
    d <- matrix(data = seq(from = 1, to = 9, by = 1), ncol = 3, nrow = 3)
    
    e <- matrix(data = seq(from = 10, to = 90, by = 10), ncol = 3, nrow = 3)
    
    f <- matrix(data = seq(from = 9, to = 1, by = -1), ncol = 3, nrow = 3)
    
    
    test_list <- list(a, b, c, d, e, f)
    

    如何对三个矩阵的每一组求和,使输出为两个矩阵,第一个是 a , b c ( output_1 d e f ( output_2

    output_1 <- structure(c(11, 12, 13, 14, 15, 16, 17, 18, 19), .Dim = c(3L, 
    3L)) 
    
    output_2 <- structure(c(3L, 6L, 9L, 12L, 15L, 18L, 21L, 24L, 27L), .Dim = c(3L, 
    3L))
    
    5 回复  |  直到 7 年前
        1
  •  4
  •   zack    7 年前
    library(purrr)
    map(split(test_list, ceiling(seq_along(test_list)/3)), ~reduce(.x , `+`))
    
    $`1`
         [,1] [,2] [,3]
    [1,]   11   14   17
    [2,]   12   15   18
    [3,]   13   16   19
    
    $`2`
         [,1] [,2] [,3]
    [1,]    3   12   21
    [2,]    6   15   24
    [3,]    9   18   27
    

    信用 to this answer 对于整洁的分裂代码。

        2
  •  2
  •   M--    7 年前

    data.table :

    data.table::rbindlist(lapply(test_list, function(x) as.data.frame(x)))[, as.list(colSums(.SD)), 
                                         by = gl(ceiling(length(test_list)*nrow(test_list[[1]])/3), 
                                         3, length(test_list)*nrow(test_list[[1]]))]
    
        3
  •  2
  •   IRTFM    7 年前

    43秒前@iod评论了我的想法。我把它作为一个与 map - reduce -扎克回答的逻辑是:

    lapply( split( test_list, cumsum( rep( c(T,F,F), 2))), function(x){ Reduce( "+", x)})
    $`1`
         [,1] [,2] [,3]
    [1,]   11   14   17
    [2,]   12   15   18
    [3,]   13   16   19
    
    $`2`
         [,1] [,2] [,3]
    [1,]    3   12   21
    [2,]    6   15   24
    [3,]    9   18   27
    

    lapply-split 而Reduce实际上是伪装的循环。

    cumsum 生成一个数值向量。使用的Masoud gl . zack 习惯于 ceiling(seq_along(test_list)/3) 并有礼貌地相信了它的灵感。

        4
  •  1
  •   iod    7 年前

    转换为数组并 apply rowSums :

    test_array<-array(c(a,b,c,d,e,f),c(3,3,6))
    apply(test_array[,1:3,1:3],2,rowSums)
    
         [,1] [,2] [,3]
    [1,]   11   14   17
    [2,]   12   15   18
    [3,]   13   16   19
    
    apply(test_array[,1:3,4:6],2,rowSums)
    
         [,1] [,2] [,3]
    [1,]    3   12   21
    [2,]    6   15   24
    [3,]    9   18   27
    
        5
  •  1
  •   r.user.05apr    7 年前

    或:

    Matrix_Number <- 6
    
    res <- vector("list", Matrix_Number / 3)
    for (i in (1:(Matrix_Number/3))) {
      res[[i]] <- test_list[[(i-1)*3 + 1]] + test_list[[(i-1)*3 + 2]] + test_list[[(i-1)*3 + 3]]
    }
    res
    
    推荐文章