Switching the order of columns of a matrix in R

Viewed 39

Suppose I generate the following fictional matrix

mat <-matrix(1:12,3)

Now I would like to rearrange the order of the columns from 1:4 to 4:1

Manually I could do this by.

Z <- cbind(mat[,4],mat[,3],mat[,2],mat[,1])

Now when the matrix becomes large with for example 30 columns, doing this manually will be a tedious process.

Does anyone have a suggestion to rewrite the order of the columns with for example a loop?

1 Answers

We can use indexing i.e. create a sequence (:) from the last column index - ncol(mat) to 1 and use that as column index

mat[, ncol(mat):1]

Or with rev

mat[, rev(seq_len(ncol(mat)))]
Related