Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ".." work to pass column names in a character vector variable?

Tags:

r

data.table

The following code does work but I cannot find any documentation about the ".." (dot dot) operator in the data.table help and vignette:

library(data.table)
cols <- c("mpg", "gear")
DT <- as.data.table(mtcars)
DT[ , ..cols]

The output is:

     mpg gear
 1: 21.0    4
 2: 21.0    4
 3: 22.8    4
 4: 21.4    3
 5: 18.7    3
...

Why does this work, is there any documentation for that?

PS: Normally I would use mget etc...

Edit 1: This is not a plain R feature of the reserved names ..., ..1, ..2 etc., which are used to refer to arguments passed down from a calling function (see ?Reserved). My example uses not a number, but characters after the two dots.

Edit 2: This is no duplicate, as the example of Rich Scriven shows:

> mtcars[, ..cols]
Error in `[.data.frame`(mtcars, , ..cols) : object '..cols' not found
like image 890
R Yoda Avatar asked Jul 28 '17 19:07

R Yoda


1 Answers

This was a new, experimental feature added in data.table v1.10.2. It is explained in the NEW FEATURES section of the data.table news for changes in v1.10.2.

It reads (quoted directly):

When j is a symbol prefixed with .. it will be looked up in calling scope and its value taken to be column names or numbers.

myCols = c("colA","colB")
DT[, myCols, with=FALSE]
DT[, ..myCols]              # same

When you see the .. prefix think one-level-up like the directory .. in all operating systems meaning the parent directory. In future the .. prefix could be made to work on all symbols apearing anywhere inside DT[...]. It is intended to be a convenient way to protect your code from accidentally picking up a column name. Similar to how x. and i. prefixes (analogous to SQL table aliases) can already be used to disambiguate the same column name present in both x and i. A symbol prefix rather than a ..() function will be easier for us to optimize internally and more convenient if you have many variables in calling scope that you wish to use in your expressions safely. This feature was first raised in 2012 and long wished for, #633. It is experimental.

Note: This answer by Arun led me to this information.

like image 173
7 revs, 2 users 97% Avatar answered Nov 19 '22 14:11

7 revs, 2 users 97%