Reputation: 635
suppose I have two data frame:
df1 = data.frame(x=1:4,y=2:5)
df2 = data.frame(x2=1:4,y2=2:5)
If I cbind df1 and df2, everything is OK
> cbind(df2,df1)
x2 y2 x y
1 1 2 1 2
2 2 3 2 3
3 3 4 3 4
4 4 5 4 5
if I cbind df2 with the 2nd column of df1, the column name will change:
> cbind(df2,df1[,2])
x2 y2 df1[, 2]
1 1 2 2
2 2 3 3
3 3 4 4
4 4 5 5
Is there anyway that I can preserve the column name?
Upvotes: 1
Views: 13427
Reputation: 887158
Here is an option using tidyverse
library(dplyr)
df1 %>%
select(y) %>%
bind_cols(df2, .)
Upvotes: 4
Reputation: 206242
Use
cbind(df2, df1[,2, drop=FALSE])
When you only select one column from a data.frame, R by default will turn it into a vector and vectors don't have "names". By using drop=FALSE
, it says a data.frame which tracks column names.
Upvotes: 6