Transforming a table in a 3D array in R

余生长醉 提交于 2021-02-18 12:34:07

问题


I have a matrix:

R> pippo.m
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
[4,]   13   14   15   16
[5,]   17   18   19   20
[6,]   21   22   23   24

and I would like to transform this matrix in a 3D array with dim=(2,4,3). Passing through the transponse of pippo.m I am able to obtain a similar result but with columns and rows rotated.

> pippo.t <- t(pippo.m)

> pippo.vec <- as.vector(pippo.t)

> pippo.arr <- array(pippo.vec,dim=c(4,2,3),dimnames=NULL)

> pippo.arr
 , , 1
     [,1] [,2]
 [1,]    1    5
 [2,]    2    6
 [3,]    3    7
 [4,]    4    8

 , , 2
     [,1] [,2]
[1,]    9   13
[2,]   10   14
[3,]   11   15
[4,]   12   16

, , 3
     [,1] [,2]
[1,]   17   21
[2,]   18   22
[3,]   19   23
[4,]   20   24

Actually, I would prefer to mantain the same distribution of the original data, as rows and colums represent longitude and latitude and the third dimension is time. So I would like to obtain something like this:

pippo.a 
, , 1
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8


, , 2
     [,1] [,2] [,3] [,4]
[1,]    9   10   11   12
[2,]   13   14   15   16


, , 3
     [,1] [,2] [,3] [,4]
[1,]   17   18   19   20
[2,]   21   22   23   24

How can I do?


回答1:


Behold the magic of aperm!

m <- matrix(1:24,6,4,byrow = TRUE)
> aperm(array(t(m),c(4,2,3)),c(2,1,3))
, , 1

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

, , 2

     [,1] [,2] [,3] [,4]
[1,]    9   10   11   12
[2,]   13   14   15   16

, , 3

     [,1] [,2] [,3] [,4]
[1,]   17   18   19   20
[2,]   21   22   23   24


来源:https://stackoverflow.com/questions/11581333/transforming-a-table-in-a-3d-array-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!