-1

I have two data frames with different columns. DataFrame1 has 8 columns and DataFrame2 has 6 columns. All DataFrame2 column names are in DataFrame1. How to add the columns with same name in both DataFrames and then keep the rest of the columns in the new DataFrame. I'm new to R so any help will be great.

Frank
  • 66,179
  • 8
  • 96
  • 180
Ankit Sharma
  • 663
  • 1
  • 5
  • 17
  • 1
    Are you asking how to merge the data frames (a la http://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right)? If not, please provide some example data frames and describe the expected output. – josliber Oct 22 '15 at 02:57

2 Answers2

2

We get the column names that are common using intersect ('nm1'), subset the two datasets based on the common column, add it, replace the columns of the first with the added values (df1[nm1] <- ..). We also replace the 'df2' common columns with the result from the previous step, create a new data.frame from both datasets that are not the common columns.

 nm1 <- intersect(colnames(df1), colnames(df2))
 df1[nm1] <- df1[nm1]+df2[nm1]
 df2[nm1] <- df1[nm1]

 df3 <- cbind(df1[setdiff(colnames(df1), nm1)], df2[setdiff(colnames(df2), nm1)]) 
akrun
  • 874,273
  • 37
  • 540
  • 662
0

I know that "code only" answers are deprecated, but this really cries out for one:

new_colname <- "newcol"
df1[[ new_colname ]] <- values
df2[[ new_colname ]] <- values
IRTFM
  • 258,963
  • 21
  • 364
  • 487