2016-04-17 7 views
3

Jede Schleife meiner Sapply-Funktion wird eine n * m-Matrix herausstellen. n ist fest, m ist nicht. Zum Beispiel, wenn ich dies in R laufen:So kombinieren Sie Matrizen mit Sapply in R

sapply(1:3, function(x) {matrix(1:9, 3)}) 

und es folgende Ausgabe:

 [,1] [,2] [,3] 
[1,] 1 1 1 
[2,] 2 2 2 
[3,] 3 3 3 
[4,] 4 4 4 
[5,] 5 5 5 
[6,] 6 6 6 
[7,] 7 7 7 
[8,] 8 8 8 
[9,] 9 9 9 

Doch was ich will, ist so etwas wie dieses:

 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] 
[1,] 1 4 7 1 4 7 1 4 7 
[2,] 2 5 8 2 5 8 2 5 8 
[3,] 3 6 9 3 6 9 3 6 9 

Jede Idee für Dies? Dank

Antwort

5

Eine Lösung ist:

do.call(cbind, lapply(1:3, function(x) {matrix(1:9, 3)})) 
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] 
[1,] 1 4 7 1 4 7 1 4 7 
[2,] 2 5 8 2 5 8 2 5 8 
[3,] 3 6 9 3 6 9 3 6 9 
1

Wir replicate

können
`dim<-`(replicate(3, matrix(1:9, 3)), c(3, 3*3)) 
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] 
#[1,] 1 4 7 1 4 7 1 4 7 
#[2,] 2 5 8 2 5 8 2 5 8 
#[3,] 3 6 9 3 6 9 3 6 9