简体   繁体   English

R - Data.table - 使用负位置按引用删除列

[英]R - Data.table - Drop columns by reference using negative position

I like data table's way of deleting columns:我喜欢数据表删除列的方式:

library(data.table)
data <- mtcars
setDT(data)
data[, 1:3 := NULL]

Deleting columns by position is not always the best solution, but it is often convenient.按位置删除列并不总是最好的解决方案,但通常很方便。 I expected this to work (delete all columns that are not in position 1:3):我希望这能工作(删除所有不在 1:3 位置的列):

data[, !1:3 := NULL]

But that returns this error:但这会返回此错误:

Error in `[.data.table`(data, , `:=`(!1:3, NULL)) : 
  LHS of := isn't column names ('character') or positions ('integer' or 'numeric')

Inspecting data in the same way does work:以相同的方式检查数据确实有效:

data[, !1:3]
    hp drat    wt  qsec vs am gear carb
 1: 110 3.90 2.620 16.46  0  1    4    4
 2: 110 3.90 2.875 17.02  0  1    4    4
 3:  93 3.85 2.320 18.61  1  1    4    1
 4: 110 3.08 3.215 19.44  1  0    3    1
...

I can do something like:我可以做这样的事情:

delCol <- colnames(data)
delCol <- tail(delCol, -3)
data[, c(delCol) := NULL]

But it is less convenient.但它不太方便。 Is there a better way?有没有更好的办法?

Of course, you can select just the first three columns, as suggested in comments.当然,您可以按照评论中的建议只选择前三列。 But if you really want to delete by reference, you might consider working with colnames :但是如果你真的想通过引用删除,你可以考虑使用colnames

library(data.table)
data <- mtcars
setDT(data)

data[, colnames(data)[-c(1:3)] := NULL]

head(data)
#>     mpg cyl disp
#> 1: 21.0   6  160
#> 2: 21.0   6  160
#> 3: 22.8   4  108
#> 4: 21.4   6  258
#> 5: 18.7   8  360
#> 6: 18.1   6  225

Alternatively, something like this would work:或者,这样的事情会起作用:

data[, setdiff(1:ncol(data), 1:3) := NULL]

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

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