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

╄→尐↘猪︶ㄣ 提交于 2020-01-31 07:07:24

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/45380628/why-does-work-to-pass-column-names-in-a-character-vector-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!