[R] Very puzzled why swapping the columns doesn't swap the column names

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Mon Jun 16 14:22:17 CEST 2008


Daren Tan wrote:
> How can I swap the column names at the same time ?
>  
>   
>> m <- cbind(x=1:3, y=2:4, z=3:5)> m     x y z[1,] 1 2 3[2,] 2 3 4[3,] 3 4 5
>> m[,c(1,2)] <- m[,c(2,1)]> m     x y z[1,] 2 1 3[2,] 3 2 4[3,] 4 3 5
>>     
what you do here is "to columns 1 and 2 put what is in columns 2 and 1,
respectively". 
what you want is "m is columns 2, 1, and 3 from m":

m = m[,c(2,1,3)]

instead of swapping column data and headers separately (you could do
that as well), swap columns.

vQ



More information about the R-help mailing list