ds_user ds_user - 4 months ago 7
R Question

Combine dataframe based on index R

I have two dataframes,

df1

Month Type Count
Jan t1 1
Feb t2 0
Mar t3 1

df2

Answer
2
3


Now, in the df2 I have answers for all the records in df1 which has Count 1. So I want to merge and get something like this.

df3

Month Type Count Answer
Jan t1 1 2
Feb t2 0 0
Mar t3 1 3


Problem is that the index for both the dataframes are different. And df1 has more records than df2. So I am not able to join based on index or merge. How do I achieve this?

Answer

You can create a column of zeros for df1 and then update values where count == 1 with the answer from df2:

df1$Answer <- 0
df1$Answer[df1$Count == 1] <- df2$Answer

df1
#  Month Type Count Answer
#1   Jan   t1     1      2
#2   Feb   t2     0      0
#3   Mar   t3     1      3