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

时间:2017-05-03 20:33:29

标签: r data.table subset

我有以下data.table

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

以及以下list

names_to_keep <- c("apple", "carrots")

我需要从data.table创建一个新的dt1,其中只包含names_to_keep中包含姓名的列。

期望的结果:

#   apple carrots
#1:     1       6
#2:     2       7
#3:     3       8
#4:     4       9
#5:     5      10

2 个答案:

答案 0 :(得分: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

或者正如@Frank评论的那样,现在有了新的语法:

dt1[,..names_to_keep]

#   apple carrots
#1:     1       6
#2:     2       7
#3:     3       8
#4:     4       9
#5:     5      10

答案 1 :(得分:0)

dt1 <- data.table(as.data.frame(dt1)[,names_to_keep])
dt1
     apple carrots
1:     1       6
2:     2       7
3:     3       8
4:     4       9
5:     5      10