Search code examples
rsliceassignment-operator

How does the `[<-` function work in R?


I've seen a couple of people using [<- as a function with Polish notation, for example

x <- matrix(1:4, nrow = 2)
`[<-`(x, 1, 2, 7)

which returns

     [,1] [,2]
[1,]    1    7
[2,]    2    4

I've tried playing around with [<- a little, and it looks like using it this way prints the result of something like x[1,2] <- 7 without actually performing the assignment. But I can't figure out for sure what this function actually does, because the documentation given for ?"[" only mentions it in passing, and I can't search google or SO for "[<-".

And yes, I know that actually using it is probably a horrible idea, I'm just curious for the sake of a better understanding of R.


Solution

  • This is what you would need to do to get the assignment to stick:

     `<-`(    `[`(   x, 1, 2), 7)  # or x <- `[<-`(   x, 1, 2, 7)
     x
         [,1] [,2]
    [1,]    1    7
    [2,]    2    4
    

    Essentially what is happening is that [ is creating a pointer into row-col location of x and then <- (which is really a synonym for assign that can also be used in an infix notation) is doing the actual "permanent" assignment. Do not be misled into thinking this is a call-by-reference assignment. I'm reasonably sure there will still be a temporary value of x created.

    Your version did make a subassignment (as can be seen by what it returned) but that assignment was only in the local environment of the call to [<- which did not encompass the global environment.