Alternating matrix rows stored in a list in R

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

Input Example:

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

$b
     [,1] [,2]
[1,]    5    7
[2,]    6    8

Expected Result:

1    3
5    7
2    4
6    8

I checked the rotation function in gdata, but this does not show this behavior for lists. Any help was appreciated.

+4
source share
2 answers

Here is a single line:

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

To understand, matrices are first stacked on top of each other using do.call(rbind, l), then the rows are extracted in the correct 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 do not have the same number of rows.

+5
source

, , , .

interleave "gdata" ..., data.frame . :

head(interleave)
# 
# 1 function (..., append.source = TRUE, sep = ": ", drop = FALSE) 
# 2 {                                                              
# 3     sources <- list(...)                                       
# 4     sources[sapply(sources, is.null)] <- NULL                  
# 5     sources <- lapply(sources, function(x) if (is.matrix(x) || 
# 6         is.data.frame(x)) 

1 3 , Gist, list interleave ( interleave)

head(Interleave)
#                                                                     
# 1 function (myList, append.source = TRUE, sep = ": ", drop = FALSE) 
# 2 {                                                                 
# 3     sources <- myList                                             
# 4     sources[sapply(sources, is.null)] <- NULL                     
# 5     sources <- lapply(sources, function(x) if (is.matrix(x) ||    
# 6         is.data.frame(x)) 

?

l <- list(a=matrix(1:4,2),b=matrix(5:8,2), c=matrix(9:12,2))
Interleave(l)
#   [,1] [,2]
# a    1    3
# b    5    7
# c    9   11
# a    2    4
# b    6    8
# c   10   12
+4

All Articles