.SD and .SDcols for the i expression in data.table join

一笑奈何 提交于 2021-02-10 02:55:57

问题


i'm trying to copy a subset of columns from Y to X based on a join, where the subset of columns is dynamic

I can identify the columns quite easily: names(Y)[grep("xxx", names(Y))] but when i try to use that code in the j expression, it just gives me the column names, not the values of the columns. the .SD and .SDcols gets pretty close, but they only apply to the x expression. I'm trying to do something like this:

X[Y[names(Y)[grep("xxx", names(Y))] := .SD, .SDcols = names(Y)[grep("xxx", names(Y)), on=.(zzz)]

is there an equivalent set of .SD and .SDcols constructs that apply to the i expression? Or, do I need to build up a string for the j expression and eval that string?


回答1:


Perhaps this will help you get started:

library(data.table)
X <- as.data.table(mtcars[1:5], keep.rownames = "id")
Y <- as.data.table(mtcars, keep.rownames = "id")
cols <- c("gear", "carb")

# copy cols from Y to X based on common "id":
X[Y, (cols) := mget(cols), on = "id"]

As Frank notes in his comment, it might be safer to prefix the column names with i. to ensure the assigned columns are indeed from Y:

X[Y, (cols) := mget(paste0("i.", cols)), on = "id"]


来源:https://stackoverflow.com/questions/43257664/sd-and-sdcols-for-the-i-expression-in-data-table-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!