The answers to another question explain how to match a string not containing a word.
The problem (for me) is that the solutions given don't work in R.
Often I create a data.frame()
from existing vectors and want to clean up my workspace. So for example, if my workspace contains:
> ls()
[1] "A" "B" "dat" "V"
>
and I want to retain only dat
, I'd have to clean it up with:
> rm(list=ls(pattern="A"))
> rm(list=ls(pattern="B"))
> rm(list=ls(pattern="V"))
> ls()
[1] "dat"
>
(where A
, B
, and V
are just examples of a large number of complicated names like my.first.vector
that are not easy to match with rm(list=ls(pattern="[ABV]"))
).
It would be most convenient (for me) to tell rm()
to remove everything except dat
, but the problem is that the solution given in the linked Q&A does 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 I match everything except dat
in R?