子列表data.table列与列表匹配

bsh*_*141 2 r subset data.table

我有以下内容data.table:

dt1 <- data.table(apple = c(1:5),
                  bananas = c(5:1),
                  carrots = c(6:10),
                  donuts = c(11:15)) 
Run Code Online (Sandbox Code Playgroud)

以下内容list:

names_to_keep <- c("apple", "carrots")
Run Code Online (Sandbox Code Playgroud)

我需要创建一个新data.tabledt1,只包括包含其名称的列names_to_keep.

期望的结果:

#   apple carrots
#1:     1       6
#2:     2       7
#3:     3       8
#4:     4       9
#5:     5      10
Run Code Online (Sandbox Code Playgroud)

Psi*_*dom 5

使用with=FALSE,另见vignette("datatable-faq"):

dt1[, names_to_keep, with=FALSE]

#   apple carrots
#1:     1       6
#2:     2       7
#3:     3       8
#4:     4       9
#5:     5      10
Run Code Online (Sandbox Code Playgroud)

或者@Frank评论说,现在有一个新的语法:

dt1[,..names_to_keep]

#   apple carrots
#1:     1       6
#2:     2       7
#3:     3       8
#4:     4       9
#5:     5      10
Run Code Online (Sandbox Code Playgroud)