tags:

views:

128

answers:

1

Hi,

I am trying to remove an object from the parent environment.

rm_obj <- function(obj){
  a <-deparse(substitute(obj))
  print (a)
  print(ls(envir=sys.frame(-1)))  
  rm(a,envir=sys.frame(-1))
}
> x<-c(1,2,3)
> rm_obj(x)

[1] "x"

[1] "rm_obj" "x"
Warning message: In rm(a, envir = sys.frame(-1)) : object 'a' not found

This will help clarify my misunderstanding regarding frames.

Thanks in advance,

Russ

+2  A: 

Your frames are right I think, it's just that rm is trying to remove a itself instead of evaluating a to get the quoted name of the variable to remove. Use the list parameter instead:

rm(list=a,envir=sys.frame(-1))
Jonathan Chang
Thanks Jonathan,That worked. Would this be a proper way of eliminating large objects after they are no longer useful?? Russ
Why not just use `rm` directly in that case?
Jonathan Chang
Oh! Now I see what Dirk meant. I am experimenting with freeing externally allocated memory (c/external-pointer) explicitly. My actual function is like free_ext_obj <-function(extptr){.Call("free_ext_obj", extptr) a <-deparse(substitute(extptr)) rm(list=a,envir=sys.frame(-1))}This allows me to free external resource and remove "extptr". I have also tried using finalizer. However, I wanted something explicit so that the externally allocated memory can be freed before gc() is invoked. Is this a reasoanble approach? This is intended more as an internal function. Thanks. Russ