How can I propperly rearrange the dimensions of a matrix?

Hello everyone. I am currently working with a matrix read from a .nc file. This matrix has dimensions of 361x201x50x31. I need to send this matrix to a code which is designed to deal with matrices of order 50x361x201x31, so I need to rearrange the matrix using the new dimensions.

I have attempted to follow these instructions, but I get an error telling me that the resize function isn't found in my computer.

I have also attempted to use dim, but if I write rdim(dataECMWF_U)<-c(50, 361, 201, 31) , then if I compare the original values evaluated at (a,b,c,d) with the values of the new matrix evaluated at (c,a,b,d), I don't get the same values, so I don't think that is the correct answer to my problem.

Can someone please offer me advice on how to proceed?
Thanks in advance.

Regards.
Jaime.

1 Like

I think you're looking for aperm().

If we use a smaller 3-way arrays to visualize what's happening:

x  <- array(1:6, 1:3)
x
#, , 1
#
#     [,1] [,2]
#[1,]    1    2
#
#, , 2
#
#     [,1] [,2]
#[1,]    3    4
#
#, , 3
#
#     [,1] [,2]
#[1,]    5    6

dim(x)
#[1] 1 2 3

y <- aperm(x, c(2,1,3))
dim(y)
#[1] 2 1 3
y
#, , 1
#
#     [,1]
#[1,]    1
#[2,]    2
#
#, , 2
#
#     [,1]
#[1,]    3
#[2,]    4
#
#, , 3
#
#     [,1]
#[1,]    5
#[2,]    6

Thank you very much for your answer. Unfortunately, when I try that I get an error

as you can see in the attached image. The error reads in english "value outside it's limits in 'perm' ".

In the attached screenshot you can see that there is no issue with the dimensions. Can you please offer me more advice please?

Regards.
Jaime.

Looking at ?aperm, you can see that the perm argument takes the index of the dimensions to permute. So it would be:

x  <- array(runif(361*201*50*31), dim = c(361,201,50,31))
dim(x)
#> [1] 361 201  50  31
y <- aperm(x, perm = c(3,1,2,4))
dim(y)
#> [1]  50 361 201  31

You should check that this permutation is what you want.

Thanks. I misundersttod what I had to do, I tought that I had to change the value of the dimensions, not the number of dimension. Thanks again.

Regards.
Jaime.

Make sure this is the permutation you need for your downstream analyses!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.