Environments in R

Sunny Avry

June 26th, 2019

Create a variables directly in the global environment

In [1]:
a <- 2
b <- 5
f <- function(x) x <- 0

Show what variables and functions are defined in the current environement

In [2]:
ls()
  1. 'a'
  2. 'b'
  3. 'f'

x is not in the global environment since it is in the environment of the function f

Get the current environment

In [3]:
environment()
<environment: R_GlobalEnv>

Get the environment of a given variable

In [4]:
pryr::where('f')
<environment: R_GlobalEnv>

Set a variable in a function in global environment

In [5]:
g <- function(y) {z <- y + 3}
g(3)
In [6]:
z # z is in the scope of the function
Error in eval(expr, envir, enclos): objet 'z' introuvable
Traceback:
In [7]:
g <- function(y) {z <<- y + 3}
g(3)
In [8]:
z #now z is the global scope
6