AdamO
AdamO

Reputation: 4930

Is the R help-file for `<<-` in fact correct?

I am trying to explain scoping and debugging for a presentation on R. I was reading the helpfile for <<- and saw it says this:

The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment.

But I don't think that quite describes what <<- does. Here is a function:

do.func <- function() {
  x <- 1
  {
    x<<-0
  }
  print(x)
}

do.func()
x

produces this output:

>     do.func()
[1] 1
>     x
[1] 0

It seems that what <<- does is go straight to the global environment. Is this correct?

Upvotes: 4

Views: 76

Answers (1)

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

Here is one attempt to make the situation more clear.

The function can be rewritten in this way:

do.func <- function() {
  `<-`(x, 1)
  `{`(x <<- 0)
  print(x)
}

Having it spelled out like that (only function calls) makes it clear what is going on. The part inside the { block in particular is composed of two functions:

`{` (`<<-`(x, 0) )

The function within:

`<<-`(variable, value)

Assigns the value to the variable and returns invisibly. For example:

> ( `<<-`(x, 2) )
[1] 2

Therefore - it is being evaluated in the same environment where the x is (in your example). So what is going on in this block:

{
  x<<-0
}  

First x is overwritten and only after that the value of x is passed to the function { which simply returns the last expression.

See also:

help(`{`)

Upvotes: 4

Related Questions