问题
I am using the cbind command in R to bind many data.frames together and each data frame has the same column names so when I bind them all, R automatically changes the column names from their original names. For example, there is a column named "X" so for each binding it renames this X.1, X.2, X.3 etc. Is there a way for me to bind them without changing any of the column names and have multiple columns with the same name?
The reason I wish to do this is so I can sort the combined data.frame after by the column names to get all the equal named columns together in the same order they were in the combined data.frame.
回答1:
To illustrate the points from my comment:
> d1 <- data.frame(a = 1:5,b = 1:5)
> d2 <- data.frame(a = letters[1:5],b = letters[1:5])
> cbind(d1,d2)
a b a b
1 1 1 a a
2 2 2 b b
3 3 3 c c
4 4 4 d d
5 5 5 e e
> data.frame(cbind(d1,d2))
a b a.1 b.1
1 1 1 a a
2 2 2 b b
3 3 3 c c
4 4 4 d d
5 5 5 e e
> x <- data.frame(cbind(d1,d2))
> sort(colnames(x))
[1] "a" "a.1" "b" "b.1"
> x[,order(colnames(x))]
a a.1 b b.1
1 1 a 1 a
2 2 b 2 b
3 3 c 3 c
4 4 d 4 d
5 5 e 5 e
来源:https://stackoverflow.com/questions/15124590/column-binding-in-r