bshelt141
bshelt141

Reputation: 1223

subset data.table columns by matching with a list

I have the following data.table:

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

and the following list:

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

I need to create a new data.table from dt1 that only includes columns who's names are included in names_to_keep.

Desired result:

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

Upvotes: 2

Views: 119

Answers (2)

akuiper
akuiper

Reputation: 214927

Use with=FALSE, also see 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

Or as @Frank commented, there's a new syntax for this now:

dt1[,..names_to_keep]

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

Upvotes: 5

Mouad_Seridi
Mouad_Seridi

Reputation: 2716

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

Upvotes: 0

Related Questions