2

I'm collecting some objects by name to save as a list in an RDS:

A = 1
B = 2
mget(c("A","B"))

If I want to pipe...

library(magrittr)
c("A","B") %>% mget                    # nope
c("A","B") %>% mget(env = globalenv()) # ok

But if I'm working inside some environment and I don't want to retype its name...

e = new.env()
e$a = 1
e$b = 2
with(e, {
  # do some stuff, then...
  c("a","b") %>% mget
})

I'm assuming I should type %>% mget(env = something), but can't figure out what (apart from e).

Frank
  • 66,179
  • 8
  • 96
  • 180
  • I'm asking more out of curiosity than an immediate need for this... – Frank Apr 21 '17 at 16:27
  • Heh, so after reading Richard Scriven's answer here http://stackoverflow.com/a/27054476/ I tried every parent.frame(n) and found that n=6 works. Go figure. – Frank Apr 21 '17 at 16:58

1 Answers1

3

You could probably get away with parent.env(environment()), as in

with( e, { c("a","b") %>% mget(env=parent.env(environment())) })
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Thanks! New variation: Can I make something like this work? `mmget <- mget; formals(mmget)[["envir"]] <- quote(parent.env(environment())); with(e, c("a","b") %>% mmget)` or is that too stupid an idea? – Frank Apr 21 '17 at 16:38
  • Anyway, if you don't know or prefer not to extend the answer to cover that, I can post a new question. I can't figure it out beyond `mmget <- mget; formals(mmget)[["envir"]] <- quote(parent.frame(7)); with(e, c("a","b") %>% mmget)` which looks incredibly fragile. – Frank Apr 21 '17 at 17:02
  • 1
    @Frank yea that sounds tricky. If you define `mmet` there, its enclosing environment would be the global, so its parent would be the base. The evaluation of `environment` needs to be delayed until its inside of the pipes environment wrapper. – Rorschach Apr 21 '17 at 17:08