0

I'm trying to use ls() with variables I've brought into a function's environment from the parent function, or the global environment. I've seen this:

How to search an environment using ls() inside a function?

And this:

rm(list = ls()) doesn't work inside a function. Why?

But I still have this problem: my ls() call is not returning the assign variables that I know are inside that function's environment. I'm not trying to get the Global Environment, I want my function's environment. What am I missing?

g = function() {
  e = environment()
  get("f",envir = parent.env(e))
  print(f)
  save(list=ls(envir = e),file = "U:/GitHub/FunctionDebug.RData")
}

h = function() {
  g()
}

f <- 1
h()

[1] 1 # So I know that my variable is seen by the function!

When I call load the file back into my Global Env, I get an empty namespace (other than e, the function environment. This only happens for variables that I've assigned from another function's environment. Why?

load("U:/GitHub/FunctionDebug.RData")
> ls()
[1] "e"
shwan
  • 538
  • 6
  • 21
  • 3
    Why haven't you assigned the results of `get` to anything? At the very least, to find something in the environment `e`, I would expect to have to explicitly assign something to that environment in the first place, no? – joran Sep 13 '18 at 22:13
  • Your variable `f` was seen by the function indeed, but there was nothing in the environment `e`. `f` was in the _parent environment_ of `e` but not in `e`. – ytu Sep 14 '18 at 02:05
  • @joran How embarrassing...that was it! I didn't realize `get` returned a value that needed to be assigned to something. – shwan Sep 14 '18 at 13:14

0 Answers0