Regex in R: match everything but not "some string" -


this question has answer here:

the answers question explain how match string not containing word.

the problem (for me) solutions given don't work in r.

often create data.frame() existing vectors , want clean workspace. example, if workspace contains:

> ls() [1] "a"   "b"   "dat" "v" > 

and want retain dat, i'd have clean with:

> rm(list=ls(pattern="a")) > rm(list=ls(pattern="b")) > rm(list=ls(pattern="v")) > ls() [1] "dat" >  

(where a, b, , v examples of large number of complicated names my.first.vector not easy match rm(list=ls(pattern="[abv]"))).

it convenient (for me) tell rm() remove except dat, problem solution given in linked q&a not work:

> rm(list=ls(pattern="^((?!dat).)*$")) error in grep(pattern, all.names, value = true) :    invalid regular expression '^((?!dat).)*$', reason 'invalid regexp' >  

so how can match except dat in r?

this remove objects except dat . (use ls argument all.names = true if want remove objects names begin dot well.)

rm( list = setdiff( ls(), "dat" ) ) 

replace "dat" vector of names, e.g. c("dat", "some.other.object"), if want retain several objects; or, if several objects can readily matched regular expression try removes objects names not start "dat":

rm( list = setdiff( ls(), ls( pattern = "^dat" ) ) ) 

another approach save data, save("dat", file = "dat.rdata"), exit r, start new r session , load data, 1oad("dat.rdata"). note this method of restarting r.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -