theforestecologist
theforestecologist

Reputation: 4917

How to get function to search in (seemingly) nested environments (in R)?

When I create a simple function that uses mget to call one object name assigned in .GlobalEnv and the other object having been assigned in the function's environment, I can't get the mget function to look in both environments.

Example:

> abc <- 5
> 
> f1 <- function(x) {
+ bcd <- 6
+ foo <- c('abc','bcd')
+ mget(foo)
+ }
>     
> f1()   
Error: value for ‘abc’ not found

Is there a way to get the mget function in this example to find both objects?

I've tried changing the envir argument for mget to many different things without any luck.


Note: I don't want to "change" the environment of the internal object (e.g., using <<- or assign(bcd,envir=.GlobalEnv).

Upvotes: 0

Views: 58

Answers (1)

xosp7tom
xosp7tom

Reputation: 2183

inherits=TRUE

f1 <- function(x) {
bcd <- 6
foo <- c('abc','bcd')
mget(foo, inherits=TRUE)
}
f1()

Upvotes: 1

Related Questions