I wonder whether there is a straight forward way to exchange any pair of columns of a matrix
in R
.
Say we want to exchange the first (i=1
) and third (j=3
) column in matrix
n=3
mat <- matrix(1:(n^2),ncol=n)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
The following always works, regardless of the size n
of the matrix
i=1; j=3
mat2 <- mat[,i]
mat[,i] <- mat[,j]
mat[,j] <- mat2
whereas direct commands like cbind(mat[,3],mat[,2],mat[,1])
(suggested in earlier threads SO1 and SO2) are limited to a given n
.
is there a more direct ways to exchange two columns i
and j
in a matrix of size n
?