2

I am trying to subset a data.table to select columns but can't seem to figure out how to do indexing from a vector.

mtcars <- data.table(mtcars )


cols <- colnames(mtcars)[c(
grep( "a" , colnames( mtcars )) ,
which(  colnames( mtcars ) =="mpg"   )
)]

# this is an error
mtcars[ , cols ]

#this is a vector - not a subsetted data.table
mtcars[ , .( cols) ]

#this too
mtcars[ , eval(cols) ]
MatthewR
  • 2,660
  • 5
  • 26
  • 37

1 Answers1

0

In dplyr this would would return the desired result: mtcars <- mtcars %>% dplyr:: select(contains("a"), "mpg")

Nick Holt
  • 116
  • 6