interleave rows of matrix stored in a list in R

后端 未结 2 555
情深已故
情深已故 2021-01-13 03:52

I want to create interleaved matrix from a list of matrices.

Example input:

> l <- list(a=matrix(1:4,2),b=matrix(5:8,2))
> l
$a
     [,1] [,         


        
2条回答
  •  天涯浪人
    2021-01-13 04:44

    Here is a one-liner:

    do.call(rbind, l)[order(sequence(sapply(l, nrow))), ]
    #      [,1] [,2]
    # [1,]    1    3
    # [2,]    5    7
    # [3,]    2    4
    # [4,]    6    8
    

    To help understand, the matrices are first stacked on top of each other with do.call(rbind, l), then the rows are extracted in the right order:

    sequence(sapply(l, nrow))
    # a1 a2 b1 b2 
    #  1  2  1  2 
    
    order(sequence(sapply(l, nrow)))
    # [1] 1 3 2 4
    

    It will work with any number of matrices and it will do "the right thing" (subjective) even if they don't have the same number of rows.

提交回复
热议问题