Beth
Beth

Reputation: 137

how to change the order of columns in a matrix in R

How to change the position of the columns in a matrix, in the manner of the last column in M, sea the first in G, the second column in M, sea the penultimate in G and so on

for example

     [,1] [,2] [,3] [,4]
[1,]    1    5    9   13
[2,]    2    6   10   14
[3,]    3    7   11   15
[4,]    4    8   12   16

and I want

     [,1] [,2] [,3] [,4]
[1,]    13    9    5   1
[2,]    14    10   6   2
[3,]    15    11   7   3
[4,]    16    12   8   4

thanks!

Upvotes: 0

Views: 537

Answers (1)

Shree
Shree

Reputation: 11150

Simplest way would be -

mat[, ncol(mat):1]

     [,1] [,2] [,3] [,4]
[1,]   13    9    5    1
[2,]   14   10    6    2
[3,]   15   11    7    3
[4,]   16   12    8    4

Upvotes: 4

Related Questions