2016-07-02 10 views
3

Lassen Sie uns ein replizierbar Beispiel machen:ändern Matrixdimension

Dies ist meine erste Matrix

d<- matrix(1:80,,5) 
d 
    [,1] [,2] [,3] [,4] [,5] 
[1,] 1 17 33 49 65 
[2,] 2 18 34 50 66 
[3,] 3 19 35 51 67 
[4,] 4 20 36 52 68 
[5,] 5 21 37 53 69 
[6,] 6 22 38 54 70 
[7,] 7 23 39 55 71 
[8,] 8 24 40 56 72 
[9,] 9 25 41 57 73 
[10,] 10 26 42 58 74 
[11,] 11 27 43 59 75 
[12,] 12 28 44 60 76 
[13,] 13 29 45 61 77 
[14,] 14 30 46 62 78 
[15,] 15 31 47 63 79 
[16,] 16 32 48 64 80 

Ich mag würde meine Matrix schneiden jeden colomn von 4 und nehmen Sie die Zahlen nach oben, wie folgt neu zu gestalten:

new.d 
    [,1] [,2] [,3] [,4] 
[1,] 1 5 9 13 
[2,] 2 6 10 14 
[3,] 3 7 11 15 
[4,] 4 8 12 16 
[5,] 17 21 25 29 
[6,] 18 22 26 30 
[7,] 19 23 27 31 
[8,] 20 24 28 32 
[9,] 33 37 41 45 
[10,] 34 38 42 46 
[11,] 35 39 43 47 
[12,] 36 40 44 48 
[13,] 49 53 57 61 
[14,] 50 54 58 62 
[15,] 51 55 59 63 
[16,] 52 56 60 64 
[17,] 65 69 73 77 
[18,] 66 70 74 78 
[19,] 67 71 75 79 
[20,] 68 72 76 80 

Irgendwelche Hilfe? Dank

Antwort

2

Wir können versuchen,

d1 <- array(d, c(4, 4, 5)) 
do.call(rbind, lapply(seq(dim(d1)[3]), function(i) d1[,,i])) 
#  [,1] [,2] [,3] [,4] 
# [1,] 1 5 9 13 
# [2,] 2 6 10 14 
# [3,] 3 7 11 15 
# [4,] 4 8 12 16 
# [5,] 17 21 25 29 
# [6,] 18 22 26 30 
# [7,] 19 23 27 31 
# [8,] 20 24 28 32 
# [9,] 33 37 41 45 
#[10,] 34 38 42 46 
#[11,] 35 39 43 47 
#[12,] 36 40 44 48 
#[13,] 49 53 57 61 
#[14,] 50 54 58 62 
#[15,] 51 55 59 63 
#[16,] 52 56 60 64 
#[17,] 65 69 73 77 
#[18,] 66 70 74 78 
#[19,] 67 71 75 79 
#[20,] 68 72 76 80 
0

Eine weitere einfache Lösung:

matrix <- matrix(seq(1,16), ncol = 4) 
rbind(matrix, 
     16+matrix, 
     32+matrix, 
     48+matrix, 
     64+matrix) 

oder:

matrix <- matrix(seq(1,16), ncol = 4) 
do.call(rbind, lapply(0:4, function(x){ 
    16*x+matrix 
    }) 
) 
3

Matrix Indizierung

# number of new columns 
cols <- 4 
matrix(t(d), ncol=cols)[matrix(1:(length(d)/cols), ncol=ncol(d), byrow=TRUE), ] 

# This almost gets us there but rows are not in correct order 
matrix(t(d), ncol=cols) 
#  [,1] [,2] [,3] [,4] 
# [1,] 1 5 9 13 
# [2,] 17 21 25 29 
# [3,] 33 37 41 45 
# [4,] 49 53 57 61 
# [5,] 65 69 73 77 
# [6,] 2 6 10 14 
# [7,] 18 22 26 30 
# [8,] 34 38 42 46 

# use this t index/group the relevant rows 
c(matrix(1:(length(d)/cols), ncol=ncol(d), byrow=TRUE)) 
# [1] 1 6 11 16 2 7 12 17 3 8 13 18 4 9 14 19 5 10 15 20 
3

Noch ein anderer Ansatz:

n = 4 
matrix(aperm(array(d, c(n, nrow(d)/n, ncol(d))), c(1, 3, 2)), ncol = nrow(d)/n) 
0

Wir können diese direkt tun

do.call(rbind,lapply(1:ncol(d),function(t) matrix(d[,t],ncol = 4)))