[R] Swap variables in data.frame

Paul Smith phhs80 at gmail.com
Mon Jun 2 14:12:51 CEST 2008


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



More information about the R-help mailing list