Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing columns in data.table using a character vector of column names

Tags:

r

data.table

Suppose I have an R data.table:

 DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)

and I have a character vector of column names that I would like to extract, or more generally operate on:

cols = c("x","y")

For example, how can I use cols to generate the equivalent of

 DT[,lapply(.SD[,list(x,y)], min) ]

Is there a way to specify the list(x,y) using the cols vector?

like image 653
DavidR Avatar asked Feb 21 '13 16:02

DavidR


People also ask

How do you access a column in a table in R?

To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.

How do you select a column in a data table?

You can also click anywhere in the table column, and then press CTRL+SPACEBAR, or you can click the first cell in the table column, and then press CTRL+SHIFT+DOWN ARROW. Note: Pressing CTRL+SPACEBAR once selects the table column data; pressing CTRL+SPACEBAR twice selects the entire table column.

What is used to identify a column in a Datatable?

By using the Column name or Column index we can identify a column in a data table.

How do I rename a column in a data table in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector.


1 Answers

You can use the data.table syntax .. which "looks up one level" (as in the Unix terminal) for the variable:

> all.equal(DT[,list(x,y)], DT[, ..cols])
[1] TRUE
> all.equal(DT[,.SD[,list(x,y)][min(v)]], DT[,.SD[ ,min(v)], .SDcols = cols])
[1] TRUE

More details under FAQ 1.6 I believe: http://datatable.r-forge.r-project.org/datatable-faq.pdf

like image 59
Chase Avatar answered Oct 06 '22 17:10

Chase