Side Effects
All functions in R return a value. Some functions also do other things: change variables in the current environment (or in other environments), plot graphics, load or save files, or access the network. These operations are called side effects.
Changes to Other Environments
We have already seen some examples of functions with side effects. In Chapter 8, we showed how to directly access symbols and objects in an environment (or in parent environments). We also showed how to access objects on the call stack.
An important function that causes side effects is the <<
- operator. This operator takes the following form:
. This operator will cause the
interpreter to first search through the current environment to find the
symbol var
<<-
value
. If the
interpreter does not find the symbol var
in the current
environment, then the interpreter will next search through the parent
environment. The interpreter will recursively search through
environments until it either finds the symbol var
or reaches the
global environment. If it reaches the global environment before the
symbol var
is found, then R will assign var
to value
in the global
environment.var
Here is an example that compares the behavior of the <-
assignment operator and the <<-
operator:
> x Error: object "x" not found > doesnt.assign.x <- function(i) {x <- i} > doesnt.assign.x(4) > x Error: object "x" not found > assigns.x <- function(i) {x <<- i} > assigns.x(4) > x [1] 4
Input/Output
R does a lot of stuff, but it’s not completely ...
Get R in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.