crazybilly
crazybilly

Reputation: 3092

Save objects in R that do not match a pattern

I'd like to save most of the objects in my global environment to a file, using save(). The objects I'd like to exclude could be matched with a simple regular expression, but as far as I can tell, the pattern argument to ls() can't use perl-style regex, so I can't use a negative look-ahead match.

Is there a straightforward way to save some objects, while excluding a few that match a regex?

Here's a toy example. In real life, the names of the objects to save vary widely and there's too many of them to try to match them all:

# objects to save
foo  <- c(1:10)
bar  <- c(10:20)
foobar  <- c(foo, bar)
asdf_uyi  <- 100
qwer2bcdefg  <- "some letters"

# don't save these
meh  <- c(20:30)
meh2  <- meh * 2

# try to save everything that DOESN'T match "meh"
#    this throws an 'Invalid regexp' error because ls() doesn't support negative lookaheads
save(file = "not-meh.RData", list = ls(pattern = ("^(?!meh)"))

Upvotes: 1

Views: 572

Answers (1)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9965

Without perl regex (you can however add perl=TRUE into the grepl(), since it would not be wrong):

save(file = "not-meh.RData", list = ls()[!grepl("^meh", ls())])

With perl negative lookup regex:

save(file = "not-meh.RData", list = ls()[grepl("^(?!meh)", ls(), perl=TRUE)])

Upvotes: 1

Related Questions