Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is := allowed as an infix operator?

Tags:

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?

like image 862
xiaodai Avatar asked Oct 09 '14 02:10

xiaodai


People also ask

What is infix operator in C?

Infix notation: X + Y. Operators are written in-between their operands. This is the usual way we write expressions. An expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C together, then multiply the result by A, then divide by D to give the final answer."

What is an infix operator in R?

Infix operators (also called “infix functions”) provide that different format, a syntax for pairing arguments while providing a mathematical order of expressions recognized by the program.

What is an infix operator in Python?

Infix operators are used in between two operands, so simple arithmetic operations such as 1 + 2 would be an infix expression where + is the infix operand. Prefix and postfix operators are either applied before or after a single operand.

What is a binary infix operator?

Most of the operators that we use in R are binary operators (having two operands). Hence, they are infix operators, used between the operands. Actually, these operators do a function call in the background.


1 Answers

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.

like image 148
MrFlick Avatar answered Nov 03 '22 22:11

MrFlick