Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match and replace elements between two dataframes

Tags:

dataframe

r

I need to replace elements from one dataframe values into another dataframe.

For example:

df1:

   id  value
0   1     10
1   2     12
2   3     54
3   4     21

df2:

   col1  col2  col3
0     1     2     3
1     1     1     3
2     1     3     4
3     1     1     5

Expected Output:

replaced values from df1 and applied to df2.

   col1  col2  col3
0    10    12    54
1    10    10    54
2    10    54    21
3    10    10     5

How to do this is in R?

Ill solve this problem in pandas like below,

dic=df1.set_index('id')['value'].to_dict()
print df2.replace(dic)

But I'm stuck in R.

Please help me to solve this problem?

like image 315
Mohamed Thasin ah Avatar asked Mar 06 '23 18:03

Mohamed Thasin ah


1 Answers

We can loop through each column of df2 using lapply and find a match for id column in df1 and replace the values for the match found using ifelse and keep the remaining values as it is.

df2[] <- lapply(df2, function(x) {
   inds <- match(x, df1$id)
   ifelse(is.na(inds),x, df1$value[inds]) 
})


df2

#  col1 col2 col3
#0   10   12   54
#1   10   10   54
#2   10   54   21
#3   10   10    5
like image 179
Ronak Shah Avatar answered Mar 24 '23 10:03

Ronak Shah