[R] Switch two rows in a matrix

Samuel Bächler linux at boeser.ch
Thu Aug 7 19:07:09 CEST 2008


Hi Zhang

>  Hi all, I have a 4 by 4 matrix, and I want to switch row 2 and row 3
>  first, then switch column 2 and column 3. Is there an easy way to do
>  it? The following is a tedious way to get what I want. But I wonder
>  if there is a way to simplify this.

'> a=matrix(rnorm(16),4,4)
'> b=a[c(2,1,3,4),]
'> a
           [,1]      [,2]        [,3]       [,4]
[1,] -0.1954458  0.299055 -1.63830678 -0.9761293
[2,] -1.0558561 -1.225412  0.06439794  0.2919717
[3,]  0.3865482  0.682090 -0.52230467 -0.5961534
[4,]  1.7555946 -0.679426 -0.57409420  1.7552651
'> b
           [,1]      [,2]        [,3]       [,4]
[1,] -1.0558561 -1.225412  0.06439794  0.2919717
[2,] -0.1954458  0.299055 -1.63830678 -0.9761293
[3,]  0.3865482  0.682090 -0.52230467 -0.5961534
[4,]  1.7555946 -0.679426 -0.57409420  1.7552651



More information about the R-help mailing list