Xin Niu
Xin Niu

Reputation: 635

r cbind a single column of a dataframe with another dataframe without changing the column name

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

Answers (3)

akrun
akrun

Reputation: 887158

Here is an option using tidyverse

library(dplyr)
df1 %>%
   select(y) %>%
   bind_cols(df2, .)

Upvotes: 4

G.Arima
G.Arima

Reputation: 1171

You can simply use cbind(df2,y=df1[,2])

Upvotes: 1

MrFlick
MrFlick

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

Related Questions