Essi
Essi

Reputation: 801

R - How to add column of data frame as column of another data frame?

I have 2 data frames, the dimensions are like this:

dim (df1)
[1] 1418    1

dim (df2)
[1] 1418    1

So I only have 1 column in each DF and the same number of rows. I want to add the 2nd data frame to the first one so that I have a dim of 1418 rows and 2 columns.

I did this:

df1[,2] = df2[,1] # and this:
dfnew = merge (df1, df2)

But it doesnt work. Any idea how to do it?

Upvotes: 0

Views: 83

Answers (2)

3pitt
3pitt

Reputation: 941

df1$addl_col<-df2$col

This should work as long as the lengths are the same (which is implied by nrow(df1)==nrow(df2)

You can also use dplyr, which has advantages of performance and chaining (and avoids some redundant syntax). Two options:

df<-mutate(df,addl_col=df2$'col')
df<-df%>%mutate(addl_col=df2$'col')

Although this is a bit unorthodox for dplyr, as seen by the necessity of the quotation marks.

Upvotes: 1

Mark
Mark

Reputation: 4537

The merge function requires that you have a shared column between the data.frames that you're combining. In your case, with only one column each, this couldn't possibly be the case.

As @Lyngbakr noted in the comments, you want to use cbind which will literally concatenate the two together. For example, dfnew = cbind(df1,df2)

cbind will work on vectors, data.frame and data.frame like objects as well as matrices.

Upvotes: 2

Related Questions