简体   繁体   中英

Transform a vector to a 3-dimensional matrix

I want this vector

v <- c(111,112,121,122,211,212,221,222)

to be transformed into a 3-dimensional matrix, so that the outcome looks like:

,,1
111 112
121 122
,,2
211 212
221 222

Using dim(v) <- c(2,2,2) results in a structure like

,,1
     [,1] [,2]
[1,]  111  121
[2,]  112  122

,,2  
     [,1] [,2]
[1,]  211  221
[2,]  212  222

I guess there is a very easy way to do this, but I guess I use the wrong keywords in Google. Thanks for your help!

It is hard to know what you are doing in general, but for your given example, I see that after dim(v) <- c(2,2,2) , the resulting array differs from your expected output by a transpose / permutation. So I do

aperm(v, c(2,1,3))

That is, we are doing:

for (i in 1:2) v[,,i] <- t(v[,,i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM