Domanda

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

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top