Sometimes I have in my R environment tens of objects and I want to keep only one, two, or three of them. As an example:
df1 df8 dataframeX
df2 df9 ObjectY
df3 df10 df15
df4 df11 df16
df5 df12 dataframeZ
df6 df13
df7 df14
I found this useful script to retain one or several objects that follow the same name pattern:
rm(list = grep("^dataframe", ls(), value = TRUE, invert = TRUE))
dataframeX
dataframeZ
However, I don't know how to modify it to keep in my R environment objects which follow different name's patterns. For example, how could I keep the objects dataframeX
, dataframeZ
and `ObjectY?.
Does anyone know how to create a script that allows me to do that easily?
You may use
rm(list = grep("^(?:dataframe|Object)", ls(), value = TRUE, invert = TRUE))
See the regex demo
Details
^
- start of string (?:
- start of a non-capturing group:
dataframe
- a dataframe
string |
- or Object
- an Object
string )
- end of grouping. The group is used to make sure the ^
is applied to both the alternatives, so that they were searched for at the start of a string only.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.