简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM