Reputation: 637
Say you have a number of objects in your R environment, such as:
a <- 4
b <- 3
c <- 2
aa <- 2
bb <- 6
cc <- 9
Now say you would like to remove the objects in your environment that are named with the letters 'a' or 'b'. This can be achieved with
rm(list = ls(pattern = "a"))
rm(list = ls(pattern = "b"))
However, imagine trying to solve this problem on a much bigger scale where you would like to remove all objects whose values appear in a list such as:
custom <- list("a", "b")
How do I apply this list as a 'looped' argument to the ls()
function?
I have experimented with:
rm(lapply(custom, function(x) ls(pattern = x)))
But this does not seem to do anything.
This feels like quite a common problem, so I fear there is an answer to this issue elsewhere on stackoverflow. Unfortunately I could not find it.
Upvotes: 1
Views: 58
Reputation: 99331
Option 1: This is a vectorized approach. Paste the custom
list together using an "or" regex separator (|
) and pass it to pattern
.
rm(list = ls(pattern = paste(custom, collapse = "|")))
Option 2: If you still want to use lapply()
, you would have to include the envir
argument in both ls()
and rm()
since lapply()
itself forms a local environment. And you would also want to put rm()
inside the lapply()
call.
lapply(custom, function(x) {
e <- .GlobalEnv
rm(list = ls(pattern = x, envir = e), envir = e)
})
Upvotes: 2
Reputation: 31452
can be done with a loop easily enough
test.a <- 4
test.b <- 3
test.c <- 2
test.aa <- 2
test.bb <- 6
test.cc <- 9
custom <- c("test.a", "test.b")
for (x in custom) rm(list = ls(pattern = x))
NB I added test. to the start of the object names, to avoid messing with peoples environment if they run this code. We don't wnat to inadvertently delete peoples actual objects named a or b etc.
Upvotes: 1
Reputation: 38500
Perhaps grep
will solve your problem:
rm(list=grep("^[ab]$", ls(), value=T))
will remove objects a and b, but nothing else.
rm(list=grep("^[ab]", ls(), value=T))
will remove objects a, aa, b, and bb, but leave c and cc in the environment.
Upvotes: 0