I want to subset a data.table by selecting specific columns. However, I don't want to specify all column names, I want to select them via a variable.
library(data.table)
dt <- data.table(x = 1:10, y = 11:20, z = 1:10)
col <- "x"
Now, I want to do something like this:
dt2 <- dt[, c(col, "y")]
This is supposed to be the same as
dt[, c("x", "y")]
However, dt2 is a character vector containing the values "x"
and "y"
I have also tried subsetting the data.table using a list
dt2 <- dt[, .(get(col), y)]
This does work, but it does not keep the column name and I need to rename that column (and possibly multiple columns if I select more columns via a variable). Is there an elegant way to do this?