data.table中的i表达式的.SD和.SDcols [英] .SD and .SDcols for the i expression in data.table join

查看:44
本文介绍了data.table中的i表达式的.SD和.SDcols的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据联接将列的子集从Y复制到X,其中列的子集是动态的

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

我可以很容易地识别列: names(Y)[grep("xxx",names(Y))] 但是,当我尝试在j表达式中使用该代码时,它只是为我提供了列名,而不是列的值. .SD .SDcols 非常接近,但它们仅适用于 x表达式.我正在尝试做这样的事情:

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 =名称(Y)[grep("xxx",names(Y)),on =.((zzz)]

是否存在适用于 i表达式的等效的 .SD .SDcols 构造集?或者,我是否需要为 j表达式 eval 该字符串构建一个字符串?

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?

推荐答案

也许这将帮助您入门:

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"]

正如弗兰克在评论中所指出的那样,为列名加上 i.可能更安全,以确保分配的列确实来自 Y :

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"]

这篇关于data.table中的i表达式的.SD和.SDcols的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆