问题
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