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
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 insideDT[...]
. It is intended to be a convenient way to protect your code from accidentally picking up a column name. Similar to howx.
andi.
prefixes (analogous to SQL table aliases) can already be used to disambiguate the same column name present in bothx
andi
. 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.
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