문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top