ahs85 ahs85 - 1 month ago 7
R Question

Rbind same data.frame with column switching

I am not new to R, but I cannot solve this problem: I have a data.frame and want to rbind the same data.frame with coloumn switching. But R does not switch the columns.

Example:

set.seed(13)
df <- data.frame(var1 = sample(5), var2 = sample(5))
> df
var1 var2
1 4 1
2 1 3
3 2 4
4 5 2
5 3 5

> rbind(df, df[,c(2,1)])
var1 var2
1 4 1
2 1 3
3 2 4
4 5 2
5 3 5
6 4 1
7 1 3
8 2 4
9 5 2
10 3 5


As you can see, the coloumns are not switched (row 6-10) whereas switching the columns alone works like a charm:

> df[,c(2,1)]
var2 var1
1 1 4
2 3 1
3 4 2
4 2 5
5 5 3


I guess this has something to do with the column names, but I cannot figure out what exacly.

Can anyone help?

Kind regards!

Answer Source

As pointed out by @Henrik, from ?rbind.data.frame: "The rbind data frame method [...] matches columns by name. So try this:

> rbind(df, setNames(df[,c(2,1)], c("var1", "var2")))
   var1 var2
1     4    1
2     1    3
3     2    4
4     5    2
5     3    5
6     1    4
7     3    1
8     4    2
9     2    5
10    5    3

this also works:

> rbind(as.matrix(df), as.matrix(df[,c(2,1)]))