首页 > 解决方案 > 如何匹配和替换两个数据框之间的元素

问题描述

我需要将一个数据帧值中的元素替换为另一个数据帧。

例如:

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

预期输出:

替换值df1并应用于df2.

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

如何在 R 中做到这一点?

我会在熊猫中解决这个问题,如下所示,

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

但我被困在R中。

请帮我解决这个问题?

标签: rdataframe

解决方案


我们可以遍历df2using的每一列lapply并在其中找到一个matchforid列,df1并替换使用找到的匹配项的值,ifelse并保持其余值不变。

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

推荐阅读