Assignments with the = Operator

The development version of R now allows some assignments to be written C- or Java-style, using the = operator. This increases compatibility with S-Plus (as well as with C, Java, and many other languages).

All the previously allowed assignment operators (<-, :=, _, and <<-) remain fully in effect. The _ is a historical curio and there seems to be general agreement that it should be phased out. (The historical origin is as follows. During the early work on S at Bell Labs, the main time-shared terminal in use was the Execuport, a heavyweight thermal-paper machine which had, among other oddities, a key corresponding to the ASCII underscore that printed as a back arrow. This was adopted as an easy-to-type and natural-looking assignment operator. The two-character back arrow was the less convenient, but portable version.) Where it is allowed, the = operator is semantically equivalent to all of the earlier assignments, except of course <<-

Limitations Imposed

The new assignments are allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.

So the following are allowed:

> y = runif(10)
> zzz = list(a=y, b="Test")
> zzz$a[1] = NA
> for(i in 1:10) { xx = min(rnorm(100)); zzz$a[i] = xx}
But the following famous C programming error is illegal in the grammar:
> if(x = 0) 1 else x
Error: syntax error
Assignments in control structures are generally dangerous; in any case, to use them you have to either use one of the older assignment operators, or add an extra level of parentheses.

There are two reasons for the restricitions:

  1. The language already has assignments with =, known as named arguments in calls. These of course continue to be interpreted as before. (They are in essence assignments in the environment created for the call.) Regualar assignments in any argument in a function call still have to be done with the old operator, or else surrounded by an extra set of parentheses.

  2. Disallowing the new assignment form in control expressions avoids programming errors (such as the example above) that are more likely with the equal operator than with other S assignments.

The restrictions do produce some other limitations that users may find less intuitive, because some functions are thought of as special. For example, the quote function.

> quote(y = 1)
[1] 1
> quote(y = 1:10)
1:10
> quote(y[1] = 1)
Error: syntax error
      
The function is implemented as a special that doesn't check argument names. The first two examples just use y as the argument name, and the third fails because the expression on the left of the = operator isn't valid as an argument name. A future revision of the function could interpret the first two, but the grammar pretty much rules out the last example.
John Chambers<jmc@research.bell-labs.com>
Last modified: Sun Dec 16 17:58:58 EST 2001