Varun
Varun

Reputation: 1321

Remove all objects from environment except those matching a given pattern

I'm trying to remove all objects from my RStudio environment where the object names are NOT equal to a pattern.

rm(list=ls(pattern!="may19"))

However this gives me an error

Error in as.environment(pos) : no item called "pattern != "may19"" on the search list

Is there another way to approach this? Thanks in advance

Upvotes: 3

Views: 764

Answers (2)

rtk19
rtk19

Reputation: 1

@Varun, NelsonGon's solution didn't work for me either. Try this instead (a combination of his two suggested lines):

rm(list = setdiff(ls(), ls(pattern = "may19"))

That should remove all objects from workspace except those with "may19".

Upvotes: 0

NelsonGon
NelsonGon

Reputation: 13319

We could use one of the following(other variants might exist, you can add all=TRUE or all.names=TRUE) for completeness:

rm(list=setdiff(ls(),"may19"))
rm(list=ls(pattern = "[^may19]"))

Upvotes: 3

Related Questions