The following function does not remove class objects obj.class
corresponding to pattern
.
keepObject <- function(pattern, obj.class, envir = .GlobalEnv){
obj <- ls(envir = envir)
obj <- obj[!grepl(pattern = pattern, obj)]
i <- unlist(lapply(obj, function(o) inherits(get(o), obj.class)))
rm(list = obj[i], envir = envir)
}
ls(pattern = "^DF")
# [1] "DF1" "DF10" "DF2" "DF3" "DF4" "DF5" "DF6" "DF7" "DF8"
#[10] "DF9"
The pattern "DF7"
corresponds to strings that contain "DF7"
. If you want you can use other regular expressions, for example "^DF7$"
.
keepObject("DF7", "data.frame")
ls(pattern = "^DF")
#[1] "DF7"
Dice.
DF1 <- data.frame(a = 1:10)
DF2 <- data.frame(a = 1:10)
DF3 <- data.frame(a = 1:10)
DF4 <- data.frame(a = 1:10)
DF5 <- data.frame(a = 1:10)
DF6 <- data.frame(a = 1:10)
DF7 <- data.frame(a = 1:10)
DF8 <- data.frame(a = 1:10)
DF9 <- data.frame(a = 1:10)
DF10 <- data.frame(a = 1:10)
Thank you. I will edit and specify my question better. Sorry.
– Bruno Avila