2017-05-03 53 views
2

我有以下data.table子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") 

我需要創建dt1只包括一個新的data.table列入名字的列表包含在names_to_keep中。

期望的結果:

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

回答

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 
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