简体   繁体   中英

how to make function in R to remove all objects from global environment except defaults and objects passed as arguments

I'm new to R (and programming in general), so I've been making various functions to warm myself up to it.

I've been trying to figure out how to make an R function that will clear my global environment of all objects except for a specified few. The code I've seen others use for this looks something like:

rm(list= ls()[!(ls() %in% c('keepThis','andThis'))],envir = )

But whenever I put this in a function (with no arguments), the function won't remove anything from the global environment. I'd like to understand why.

I've had more luck with:

clean <- function(except){
    except = ifelse(is.character(except), except, deparse(substitute(except)))
    rm(list=setdiff(ls(envir=.GlobalEnv), c(except,"clean")), envir=.GlobalEnv)
}

But I can't figure out how to modify this one to allow me to save more than two objects at a time.

Ideally, I would love to have a function that would save several specified objects by default, as well as any objects passed as arguments. Is this even possible?

I think this function may help:

rm.except <- function(except, pattern) {
  except = except
  pattern = pattern
  formula = c(c(except), ls(pattern = pattern, envir = .GlobalEnv))
  rm(list = setdiff(ls(envir = .GlobalEnv), formula), envir = .GlobalEnv)
}  

ls() in my environment:

 [1] "a"          "al"         "b"          "c"          "corrmatrix" "counts"    
 [7] "d"          "df1"        "df2"        "e"          "f"     

I want all objects to be removed; except for objects a, b, c, d and those objects containing df ;

rm.except(except = c("a", "b", "c", "d"), pattern = "df")  

ls() will be:

[1] "a"   "b"   "c"   "d"   "df1" "df2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM