Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 947
user1971988 Avatar asked Jul 24 '13 09:07

user1971988


1 Answers

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.

like image 113
Roland Avatar answered Oct 07 '22 14:10

Roland