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
278 views
in Technique[技术] by (71.8m points)

r - Why is := allowed as an infix operator?

I have come across the popular data.table package and one thing in particular intrigued me. It has an in-place assignment operator

:=

This is not defined in base R. In fact if you didn't load the data.table package, it would have raised an error if you had tried to used it (e.g., a := 2) with the message:

Error: could not find function ":="

Also, why does := work? Why does R let you define := as infix operator while every other infix function has to be surrounded by %%, e.g.

`:=` <- function(a, b) {
   paste(a,b)
}

"abc" := "def"

Clearly it's not meant to be an alternative syntax to %function.name% for defining infix functions. Is data.table exploiting some parsing quirks of R? Is it a hack? Will it be "patched" in the future?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It is something that the base R parser recognizes and seems to parse as a left assign (at least in terms or order of operations and such). See the C source code for more details.

as.list(parse(text="a:=3")[[1]])
# [[1]]
# `:=`
# 
# [[2]]
# a
# 
# [[3]]
# [1] 3

As far as I can tell it's undocumented (as far as base R is concerned). But it is a function/operator you can change the behavior of

`:=`<-function(a,b) {a+b}
3 := 7
# [1] 10

As you can see there really isn't anything special about the ":" part itself. It just happens to be the start of a compound token.


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

...