[R] issue with using rm: cannot generate on-the-fly list

Duncan Murdoch murdoch at stats.uwo.ca
Thu Dec 17 15:08:05 CET 2009


On 17/12/2009 5:33 AM, Cormac Long wrote:
> Hello,
> 
> I have the following problem when trying to use rm:
> 
> In a top level script file I have a loop iterating over some index. The loop
> is not contained within a function, so the scope of variables declared in
> the loop is global. Within this loop I generate several variables which
> should be removed at the end of each iteration. To do this, I wrote a
> function to clean up the workspace. An example is included here:
> 
> cleanUpWorkspace<-function()
> {
>     #Remove key data sructures, if they have been declared:
>     delList<-list()
>     for(varname in c("rv1","rv2", "rv3", "rv4")) {
>         if(exists(varname)) {
>             delList<-append(delList, varname)
>         }
>     }
>     if(length(delList)>0) {
>         rm(list=delList, pos=-1)
>         #rm(list=delList, envir=parent.env(environment()))
>         #rm(list=delList, envir=globalenv())
>     }
> }
> 
> Unfortunately, this fails to work - it aborts with the following error:
> Error in rm(list = delList, pos = -1) : invalid first argument
> if I use rm(list=delList, pos=-1)

Your delList is a list.  Despite the name of the argument, it doesn't 
want a list, it wants a character vector.  So create it as character(0),
and append elements using delList <- c(delList, varname).

BTW, I'd recommend using the envir=globalenv() version of your rm() 
call, as it says most clearly that your function is messing with the 
global environment.  But first I'd recommend not messing with the global 
environment; think of some other way to share data between functions, 
e.g. defining them all in the same environment, etc.

Duncan Murdoch

> 
> Or with the following error:
> Error in rm(list = delList, evir = parent.env(environment())) :
>   ... must contain names or character strings
> if I use rm(list=delList, envir=parent.env(environment())) or
> rm(list=delList, envir=globalenv())
> 
> I get the same errors if I bypass rm entirely and use
> .Internal(remove(delList, globalenv(),FALSE)).
> 
> I am using R version 2.10.0 running on a windows 7 box.
> 
> I want to declare the clean-up within a function for design purposes. The
> full project is spread over several files and I am trying to keep the main
> loop as simple as possible.
> 
> Sincerly,
> Cormac Long.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list