[R] How to remove all objects except a few specified objects?

Joshua Wiley jwiley.psych at gmail.com
Tue Aug 24 16:27:51 CEST 2010


If you are going to be doing this a lot, you may want to consider
making a little function.  Here is an example 'do not remove'
function.  It defaults to the global environment, but you can always
change it.  Also, if you try to keep a variable name that does not
exist, it will throw an error and not remove anything.  My assumption
is that when one of the names the user typed does not match a current
object, the user made a typo.

dnrm <- function(vars, envir = .GlobalEnv) {
  vars <- c(vars, "dnrm")
  keep <- match(x = vars, table = ls(envir = envir))
  if(any(is.na(keep))) {
    stop(paste("Some of the variables were not found in",
             environmentName(envir)))
  }
  rm(list = ls(envir = envir)[-keep], envir = envir)
  cat("Removed all but", length(keep), "objects from",
      environmentName(envir), fill = TRUE)
}

Cheers,

Josh

On Mon, Aug 23, 2010 at 12:00 PM, Cheng Peng <cpeng at usm.maine.edu> wrote:
>
> How to remove all R objects in the RAM except for a few specified ones?
> rm(list=ls()) removes all R objects in the R work space.
>
> Another question is that whether removing all R objects actually releases
> the RAM? Thanks.
> --
> View this message in context: http://r.789695.n4.nabble.com/How-to-remove-all-objects-except-a-few-specified-objects-tp2335651p2335651.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list