Search code examples
rsubsetenvironment

How to subset an environment by its variable names in r


I would like to subset an environment by its variable names.

e <- new.env(parent=emptyenv())
e$a <- 1
e$b <- 2
e$d <- 3
e[ls(e) %in% c("a","b", "c")]
### if e was a list, this would return the subset list(a=1, b=2)

I could not figure out how to subset elements of an environment by their names. Using lapply or eapply does not work either. What is the proper or easy way to subset an environment by its variable names? Thank you.


Solution

  • Okay, after thinking this through a bit more, may I suggest:

    mget(c("a","b"), envir=e)
    #$a
    #[1] 1
    #
    #$b
    #[1] 2