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.
我不是R的新手,但是我无法解决这个问题:我有一个data.frame并希望使用coloumn切换来匹配相同的data.frame。但是R不会切换列。
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:
如你所见,coloumns没有切换(第6-10行),而单独切换列就像一个魅力:
> 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.
我想这与列名有关,但我无法弄清楚什么是exacly。
Can anyone help?
有人可以帮忙吗?
Kind regards!
亲切的问候!
1 个解决方案
#1
1
As pointed out by @Henrik, from ?rbind.data.frame
: "The rbind
data frame method [...] matches columns by name. So try this:
正如@Henrik所指出的,来自?rbind.data.frame:“rbind数据框方法[...]按名称匹配列。所以试试这个:
> 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)]))
#1
1
As pointed out by @Henrik, from ?rbind.data.frame
: "The rbind
data frame method [...] matches columns by name. So try this:
正如@Henrik所指出的,来自?rbind.data.frame:“rbind数据框方法[...]按名称匹配列。所以试试这个:
> 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)]))