[R] clear R-objects inside a function?

Douglas Bates bates at stat.wisc.edu
Tue Apr 10 16:38:50 CEST 2001


Paul E Johnson <pauljohn at ukans.edu> writes:

> Using RedHat Linux 7.0, R-1.2.2, R-hdf5-1.2 library, 
> 
> I want to load a dataset, do some stuff with it, then erase its objects,
> get an other, repeat.  My friend wrote a function which tried to clear
> away all the objects. At the end, it uses rm() to remove objects. This
> is the same way we do it interactively, from the R prompt:
> 
> testLoadSeveralHDF <- function(numFiles) {
>   for (i in 0:(numFiles-1)) {
>     filename <- paste("trial",i,".hdf",sep="")
>     print(filename)
>     hdf5load(filename)
>     rm(list = ls(pat="g*"))   
>   }
> }
> 
> However, after that program runs, the g* objects are not erased, but
> typing "rm(list=ls(pat="g*")) from the command line does erase them.  I
> realized there's something about the environment that I need to tell the
> function, I just don't know what?

Add envir = .GlobalEnv to both the ls and the rm calls.  That is

     rm(list = ls(pat = "g*", envir = .GlobalEnv), envir = .GlobalEnv)
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list