[英]How to update selected rows in a data.table if they match value from another data.table
I would like to find a data.table solution for updating selected rows from values in another table:我想找到一个 data.table 解决方案,用于从另一个表中的值更新选定的行:
Table 1 looks like this表 1 看起来像这样
id var grade
1 var1 X
2 var2 B
3 var3 X
4 var4 D
5 var5 X
Table 2表 2
id var grade
1 var1 Y
2 var2 B2
3 var3 Y
4 var4 D2
5 var5 Y
the updated table 1 looks like this更新后的表 1 如下所示
id var grade
1 var1 Y
2 var2 B
3 var3 Y
4 var4 D
5 var5 Y
any help is much appreciated任何帮助深表感谢
We can just use second dataset and remove the digits at the end我们可以只使用第二个数据集并删除最后的数字
df2$grade <- sub("\\d+$", "", df2$grade)
Or in data.table
, convert the first data.frame to 'data.table', and assign 'grade' with the second datasets 'grade' joined by 'id', 'var' and remove the digits at the end或者在
data.table
,将第一个 data.frame 转换为 'data.table',并将第二个数据集 'grade' 分配给 'grade',由 'id', 'var' 连接并删除末尾的数字
library(data.table)
setDT(df1)[df2, grade := i.grade, on = .(id, var)][, grade := sub("\\d+$", "", grade][]
Or as @IceCreamToucan commented或者正如@IceCreamToucan 评论的那样
setDT(df1)[df2, grade := sub("\\d+$", "", i.grade), on = .(id, var)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.