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

From: jim holtman <jholtman_at_gmail.com>
Date: Mon, 16 Jun 2008 08:18:21 -0400

What you are doing with the assignment

m[,c(1,2)] <- m[,c(2,1)]

is only changing the values in the matrix; it knows nothing about the names. If you want the names of the columns switched, then you have to do it:

> 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

> colnames(m)[c(1,2)] <- colnames(m)[c(2,1)]
> m

     y x z

[1,] 2 1 3
[2,] 3 2 4
[3,] 4 3 5

>

On Mon, Jun 16, 2008 at 8:10 AM, Daren Tan <daren76_at_hotmail.com> 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
> _________________________________________________________________

>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Mon 16 Jun 2008 - 12:27:57 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 16 Jun 2008 - 12:30:44 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive