Sven Hager
Sven Hager

Reputation: 3204

R: environment lookup

I am a bit confused by R's lookup mechanism. When I have the following code

# create chain of empty environments
e1 <- new.env()
e2 <- new.env(parent=e1)
e3 <- new.env(parent=e2)

# set key/value pairs
e1[["x"]] <- 1
e2[["x"]] <- 2

then I would expect to get "2" if I look for "x" in environment e3. This works if I do

> get(x="x", envir=e3)
[1] 2

but not if I use

> e3[["x"]]
NULL

Could somebody explain the difference? It seems, that

e3[["x"]]

is not just syntactic sugar for

get(x="x", envir=e3)


Thanks in advance,
Sven

Upvotes: 6

Views: 837

Answers (1)

Andrie
Andrie

Reputation: 179558

These functions are different.

get performs a search for an object in an environemnt, as well as the enclosing frames (by default):

From ?get:

This function looks to see if the name x has a value bound to it in the specified environment. If inherits is TRUE and a value is not found for x in the specified environment, the enclosing frames of the environment are searched until the name x is encountered. See environment and the ‘R Language Definition’ manual for details about the structure of environments and their enclosures.

In contrast, the [ operator does not search enclosing environments, by default.

From ?'[':

Both $ and [[ can be applied to environments. Only character indices are allowed and no partial matching is done. The semantics of these operations are those of get(i, env=x, inherits=FALSE).

Upvotes: 9

Related Questions