Home > Software design >  Copy column from one data.frame to another based on index
Copy column from one data.frame to another based on index

Time:05-15

The problem is similar to what posted in Combine dataframe based on index R

I am trying to copy one column from df2 (huge df) to df1 (small df) but based on index. In python it would be:

df1= df1[df.index.isin(df2.index)]
df1['columnx'] = df2['columny']

df1$name <- 0
df1$name[df1$df1['columnx'] == df2$['columny'] <- df2$name

I tried to replace the "name" column in df1 with the values of df2 "name" column corresponding to common index (columnx \ columny as index col) but have failed. I also tried to find a common index

df2.index <- intersect(df1$columnx, df2$columny)

so df2 will have a small index as in df1 and then to copy the column from df2 to df1, but it doesn't work

EDIT:

DF1

   columnx   |     col.1     |    col.2   |...
       a     |      12345    |   etc.     |...
       b     |               |            |

DF2

columny   | col.1  | col.2  | name|
a         | 123    | 1234   |abc  |
b         |        |        |def  |
c         |        |        |ghi  | 
d         |        |        |     |
..

Result needed:

DF combined:

   columnx   |     col.1     |    col.2   |name
       a     |      12345    |   etc.     |abc  |
       b     |               |            |def  |

CodePudding user response:

You can simply use match():

df1$name <- df2$name[match(df1$columnx, df2$columny)]

or merge the both data by common columns:

dplyr::left_join(df1, df2[c("columny", "name")], by = c("columnx" = "columny"))
  • Related