简体   繁体   English

R data.table:.SD 的名称不可用于分配

[英]R data.table: names of .SD not available for assignment

Often, I want to manipulate several variables in a DT and I need to select the column names based on their names or class.通常,我想在 DT 中操作多个变量,我需要 select 列名基于它们的名称或 class。

d <- data.table(x = 1:10, y= letters[1:10])

# My usual approach
col <- str_subset(names(d), '^x')
d[, (col) := 2:11]

However, it would be very useful and less verbose to do this:但是,这样做会非常有用且不那么冗长:

 d[, (names(.SD)) := 2:11, .SDcols = patterns('^x')]

But this throws an error:但这会引发错误:

Error in `[.data.table`(d, , `:=`((names(.SD)), 2:11), .SDcols = patterns("^x")) : 
  LHS of := isn't column names ('character') or positions ('integer' or 'numeric')
> 

The column names of.SD are available, though: .SD 的列名可用,但是:

> d[, names(.SD), .SDcols = patterns('^x')]
[1] "x"

Why aren't the names of.SD available for assignment on the LHS of:=?为什么 .SD 的名称不能在 := 的 LHS 上赋值?

As noted this is not yet possible.如前所述,这还不可能。 The workaround only adds one line of code:解决方法只添加一行代码:

cols = grep('^x', names(d))
d[ , (cols) := 2:11, .SDcols = cols]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM