Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...