简体   繁体   English

如果 data.table 中的选定行与另一个 data.table 中的值匹配,如何更新它们

[英]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.

相关问题 如何将一个data.table中的列中的某些行添加到标题下的另一个data.table中? - How to add certain rows from a column in one data.table to another data.table under a heading? 如何从一个data.table中选择行以应用于另一data.table? - How to select rows from one data.table to apply in another data.table? 根据另一个data.table删除data.table中的行 - Remove rows in data.table according to another data.table 在 data.table 中:迭代另一个 data.table 的行 - In data.table: iterating over the rows of another data.table 根据另一个data.table中的值填充data.table - fill a data.table based on value in another data.table 当唯一的行ID和列名匹配时,从另一个data.table中减去data.table - Subtract data.table from another data.table when unique row ID and column names match R:根据另一个data.table有效地从data.table中选择指定的行? - R: efficiently select specified rows from a data.table according to another data.table? 使用另一个data.table中的值更新data.table中的值 - Update values in data.table with values from another data.table 使用来自另一个 data.table 列的值更新 data.table 列中值的子集 - Update a subset of values in data.table column with values from another data.table column 如何选择同时匹配另一个data.table中的两个条件的data.table中的行? - How to select rows in a data.table matching simultaneously two conditions in another data.table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM