user1971988
user1971988

Reputation: 873

How to obtain objects in the environment of the calling function in R?

test <- function(){    
a = 3
b = c(1,2,3)
c = matrix(-99, 3, 4)
print(getObjects())
}

getObjects <- function(){
return(ls(pos=1))
}

I want the function test to print out only a, b, c, since those are the only objects in the scope of the function test() (it is fine it prints other objects/functions accessed by test e.g. getObjects() in this case). But no choice of pos is giving me that? Is there a way to get objects in the "calling" function (here, test), so that I can do some manipulation on that and the "called" function (here getObjects) can return the results. My function getObjects is supposed to manipulate on the objects obtained by doing an ls().

Upvotes: 6

Views: 1962

Answers (1)

Roland
Roland

Reputation: 132706

test <- function(){    
  a = 3
  b = c(1,2,3)
  c = matrix(-99, 3, 4)
  print(getObjects())
}

getObjects <- function(){
  return(ls(envir=parent.frame(n = 1)))
}

test()
#[1] "a" "b" "c"

Of course you could simply use the defaults for ls:

test <- function(){    
  a = 3
  b = c(1,2,3)
  c = matrix(-99, 3, 4)
  ls()
}

From the documentation:

name: which environment to use in listing the available objects. Defaults to the current environment.

Upvotes: 7

Related Questions