Skip to Content
R in a Nutshell
book

R in a Nutshell

by Joseph Adler
January 2010
Beginner
634 pages
19h 50m
English
O'Reilly Media, Inc.
Content preview from R in a Nutshell

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: var <<- value. This operator will cause the interpreter to first search through the current environment to find the symbol var. 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.

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R in a Nutshell, 2nd Edition

R in a Nutshell, 2nd Edition

Joseph Adler
The Big R-Book

The Big R-Book

Philippe J. S. De Brouwer
R Packages

R Packages

Hadley Wickham

Publisher Resources

ISBN: 9781449377502Supplemental ContentErrata Page