R: environment search

I am a little confused by the search engine R. 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 a "2" if I searched for an "x" in an e3 environment. It works if I do

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

but not if i use

 > e3[["x"]] NULL 

Can someone explain the difference? It seems that

 e3[["x"]] 

is not just syntactic sugar for

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


Thanks in advance,
Sven

+6
source share
1 answer

These functions are different.

get searches for an object in the environment, as well as enclosing frames (by default):

From ?get :

This function checks if the name x has a value associated with it in the specified environment. If TRUE inherits and the value is not found for x in the specified environment, the environments surrounding the environment are searched until the name x is found. See the Environment section and the R Language Definition Guide for more information on the structure of environments and their enclosures.

In contrast, the [ operator does not search for the default environment.

From ?'[' :

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

+9
source

Source: https://habr.com/ru/post/913903/


All Articles