r - 如何匹配和替换两个数据框之间的元素
问题描述
我需要将一个数据帧值中的元素替换为另一个数据帧。
例如:
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中。
请帮我解决这个问题?
解决方案
我们可以遍历df2
using的每一列lapply
并在其中找到一个match
forid
列,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
推荐阅读
- python - Is there a non-math version of matplotlib.ticker.LogFormatterSciNotation?
- bash - Bash: getting all lines in a file matching with a string or another one (and keeping the order)
- python - How to store information from JSON files in cache using Python?
- c# - 了解 Dapper splitOn
- openpyxl - Openpyxl,明智地搜索值列。
- javascript - 单元测试没有通过,即使它显然应该通过?
- xmpp - node-xmpp-server vs node-xmpp-client
- laravel-5 - Laravel 获取符合不同模型条件的集合
- wordpress - 在wordpress中匹配搜索结果后识别ACF字段
- python - matplotlib.animation 巨大的图像