O'Reilly logo

R in a Nutshell, 2nd Edition by Joseph Adler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Environments and Functions

When a function is called in R, a new environment is created within the body of the function, and the arguments of the function are assigned to symbols in the local environment.[23]

As an example, let’s create a function that takes four arguments and does nothing except print out the objects in the current environment:

> env.demo <- function(a, b, c, d) {print(objects())}
> env.demo(1, "truck", c(1,2,3,4,5), pi)
[1] "a" "b" "c" "d"

Notice that the objects function returns only the objects from the current environment, so the function env.demo only prints the arguments defined in that environment. All other objects exist in the parent environment, not in the local environment.

The parent environment of a function is the environment in which the function was created. If a function was created in the execution environment (for example, in the global environment), then the environment in which the function was called will be the same as the environment in which the function was created. However, if the function was created in another environment (such as a package), then the parent environment will not be the same as the calling environment.

Working with the Call Stack

Although the parent environment for a function is not always the environment in which the function was called, it is possible to access the environment in which a function was called.[24] Like many other languages, R maintains a stack of calling environments. (A stack is a data structure in which ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required