2017-11-25 1 views
0

Ich entschuldige mich für meine dumme Frage, aber ich fange gerade an, sich mit Arrays vertraut zu machen.Drehen Sie Matrizen in Array um 90 Grad

Ich muss nur die Matrizen in meinem Array um 90 Grad drehen.

Hier einige Daten und was ich versuchte, so weit:

mat1 = as.matrix(data.frame(col1 = c(1,2,3,4,5,6,7,8), col2 = c(2,3,'NA',5,6,7,8,9), col3 = c(3,4,5,6,7,8,9,10), col4 = c(2,3,4,1,2,6,7,8), 
          col5 = c(2,3,'NA','NA',6,7,8,9), col6 = c(1,2,3,5,6,7,8,9), col7 = c(1,2,3,4,6,7,'NA','NA'))) 


mat2 = as.matrix(data.frame(col1 = c('NA',2,3,4,5,6,7,8), col2 = c(2,3,1,5,6,7,8,9), col3 = c(3,4,5,6,7,8,9,'NA'), col4 = c(2,3,4,1,2,6,7,8), 
          col5 = c(2,3,11,88,6,7,8,9), col6 = c(1,2,3,5,6,7,8,9), col7 = c(1,2,3,4,6,7,'NA','NA'))) 

#ignore warnings 
class(mat1) = 'numeric' 
class(mat2) = 'numeric' 

my_array = array(c(mat1, mat2), dim = c(8,7,2)) 

Was ich müde ohne Erfolg:

library(pracma) 

ar_rot = array(dim=c(8,7,2)) 

for (i in 1:2) { 
    ar_rot[,,i] = rot90(my_array[,,i], k = 1) 
} 

Ich denke, die Probleme in den Indizes von ar_rot liegt, denn wenn ich die Anwendung gleicher Code zu nur einer Matrix z

ar_rot_1 = rot90(my_array[,,1], k = 1) 

es funktioniert! aber mein Array hat Tausende von Matrizen!

Irgendwelche Hinweise? Dank

+1

Für diesen einfachen Fall könnten Sie auch, Experiment mit 'aperm' - z Hier scheint 'aperm (mein_array, c (2, 1, 3)) [dim (mein_array) [2]: 1,,]' zu funktionieren, obwohl ich nicht sicher bin, wie flexibel eine Lösung ist, die du brauchst –

Antwort

0

fand ich einen Weg, um meine Frage durch das Array in eine Liste konvertieren, die Funktion anwenden und dann die Liste Array konvertieren zurück:

lst = lapply(seq(dim(my_array)[3]), function(x) my_array[ , , x]) #convert to list 
lst = lapply(lst, function(x) rot90(x, 1)) #rotate 

#convert list back to array 
ar_rot = array(as.numeric(unlist(lst)), dim=c(7, 8, 2)) 

> print(ar_rot) 
, , 1 

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

, , 2 

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] 
[1,] 1 2 3 4 6 7 NA NA 
[2,] 1 2 3 5 6 7 8 9 
[3,] 2 3 11 88 6 7 8 9 
[4,] 2 3 4 1 2 6 7 8 
[5,] 3 4 5 6 7 8 9 NA 
[6,] 2 3 1 5 6 7 8 9 
[7,] NA 2 3 4 5 6 7 8 
Verwandte Themen