我有以下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
答案 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