Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific column selection from data.table in R

Tags:

r

data.table

I have a data.table in R. The table has column names. I have a vector named colnames with a few of the column names in the table.

colnames<-c("cost1", "cost2", "cost3")

I want to select the columns whose names are in the vector colnames from the table. The name of the table is dt.

I have tried doing the following:

selected_columns <- dt[,colnames]

But this, does not work, and I get an error.
However, when I try the following, it works:

selected_columns <- dt[,c("cost1", "cost2", "cost3")]

I want to use the vector variable (colnames) to access the columns and not the c("..") method.
How can I do so?

like image 878
big tree Avatar asked Sep 04 '26 10:09

big tree


1 Answers

You can try like this:

dt[, .SD, .SDcols = colnames]

Meanwhile, data.table gives an alternative choice in recent version:

dt[, ..colnames]
like image 93
Ray Stylee Avatar answered Sep 06 '26 01:09

Ray Stylee