0

Problem

In R, you can assign an attribute like so:

attr(x, "foo") <- "bar"

I get what this does, but I'm trying to understand how this statement breaks down into more fundamental pieces of the R language.

Thoughts

While attr is a function, it appears to also be a part of the fundamental language grammar, since you cannot do this:

t = attr
t(x, "bar") <- "baz" # gives an error

The most similar syntax I can think of is in PHP, where you can assign by "calling" the list "function" like this:

list($a, $b) = array(1, 2);

I understand the above line to have the following grammar:

list_assignment:
    list(<var>...) = <expression>;

It would seem to make sense that in R, the grammar is defined similarly:

attr_assignment:
    attr(<var>, <expression>) <- <expression>;

But you can also write this:

x = `attr<-`(x, "bar", "baz")

Which seems that it would require one of the following:

  • Special support for `attr<-`(<var>, <expr>, <expr>) in the grammar
  • A real function named attr<- which does the same as attr(...) <- under the hood

Summary

How should this attr assignment should be thought about in terms of simpler language elements? What about `attr<-`? Additionally, how are these implemented within the R parser?

Chris Middleton
  • 5,654
  • 5
  • 31
  • 68
  • 2
    `attr<-` is a separate function. There are numerous such "assignment" functions defined in R. They are all implemented as separate functions, so if you ever want both `foo()` and `foo() <- bar` to work you have to write two functions. I can't tell you the details of how the parser recognizes them, but I know that it does. – joran Mar 04 '19 at 16:19
  • @joran Thanks to your comment I found a section in Hadley Wickham's Advanced R that explains what's going on. It seems that the R language converts any expression like `blah(...) <- ` into a call to \`blah<-\`(), so the former is just syntactic sugar for the latter. Feel free to post an answer. https://adv-r.hadley.nz/functions.html#replacement-functions – Chris Middleton Mar 04 '19 at 16:26
  • 1
    @ChrisMiddleton, you can also find this described in the documents that come with R, hidden in section 3.4.4 of the R Language Definition. – user2554330 Mar 04 '19 at 17:26

0 Answers0