Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a vector to a matrix in R starting from the bottom to top

I have a vector x = c(1,2,3,1,2,0,1,0,0). I want to convert it to a matrix starting from the bottom to the top. That is, I need to fill out the entries of the matrix starting from the last entry of each column.

I tried the following:

x <- c(1,2,3,1,2,0,1,0,0) 
M2 <- matrix(x, 3, 3) 
M2
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    0
[3,]    3    0    0

However, I need it as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

M2
     [,1] [,2] [,3]
[1,]    3    0    0
[2,]    2    2    0
[3,]    1    1    1

>Solution :

We could use apply and the rev function:

apply(M2, 2, rev)

    [,1] [,2] [,3]
[1,]    3    0    0
[2,]    2    2    0
[3,]    1    1    1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading