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?
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.
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.
By using the Column name or Column index we can identify a column in a data table.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With