如何在两个数据框之间匹配和替换元素

时间:2018-07-20 09:11:58

标签: r dataframe

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

例如:

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中。

请帮助我解决这个问题?

3 个答案:

答案 0 :(得分:3)

我们可以使用df2遍历lapply的每一列,并在match的{​​{1}}列中找到id,并替换找到的匹配项的值使用df1并保持其余值不变。

ifelse

答案 1 :(得分:2)

在创建第二个数据集的副本之后,我们可以使用命名向量来实现此目的。

df3 <- df2
df3[] <- setNames(df1$value, df1$id)[as.matrix(df2)]
i1 <- is.na(df3)
df3[i1] <- df2[i1] 
df3
#  col1 col2 col3
#0   10   12   54
#1   10   10   54
#2   10   54   21
#3   10   10    5

答案 2 :(得分:2)

您可以做什么:

复制df2:

df3=df2 # in R this is  a copy not as in python
df3[]=df1$value[match(as.matrix(df2),df1$id)] # Match the columns
df3[is.na(df3)]=df2[is.na(df3)] # Reset Na to the previous value
df3
  col1 col2 col3
0   10   12   54
1   10   10   54
2   10   54   21
3   10   10    5