[R] Swap variables in data.frame

Birgitle birgit.lemcke at systbot.uzh.ch
Mon Jun 2 14:41:25 CEST 2008


That works perfect.

Thanks a lot Paul!

Greets

Birgit


Paul Smith wrote:
> 
> On Mon, Jun 2, 2008 at 1:04 PM, Birgitle <birgit.lemcke at systbot.uzh.ch>
> wrote:
>>
>> Thanks Paul.
>>
>> I am not sure if I understood well, but when I do it then I have only two
>> columns left:
>>
>>> L3 <- LETTERS[1:3]
>>> (d <- data.frame(cbind(x=1, y=1:10, z=11:20), fac=sample(L3, 10,
>>> replace=TRUE)))
>>   x  y  z fac
>> 1  1  1 11   C
>> 2  1  2 12   B
>> 3  1  3 13   B
>> 4  1  4 14   C
>> 5  1  5 15   C
>> 6  1  6 16   B
>> 7  1  7 17   C
>> 8  1  8 18   C
>> 9  1  9 19   B
>> 10 1 10 20   C
>>> d <- d[,c(2,1)]
>>> d
>>    y x
>> 1   1 1
>> 2   2 1
>> 3   3 1
>> 4   4 1
>> 5   5 1
>> 6   6 1
>> 7   7 1
>> 8   8 1
>> 9   9 1
>> 10 10 1
>>
>> But I have more than two columns in my data.frame.
> 
> In your case, it should be
> 
> # Swap the two first columns
> d <- d[,c(2,1,3,4)]
> # Swap column 2 and 3
> d <- d[,c(1,3,2,4)]
> 
> Notice that my data frame had only two columns.
> 
> Paul
> 
> ______________________________________________
> 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.
> 
> 
Bb205Lc

-----
The art of living is more like wrestling than dancing.
(Marcus Aurelius)
-- 
View this message in context: http://www.nabble.com/Swap-variables-in-data.frame-tp17597476p17600374.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list