How do I clear only a few specific objects from the workspace?

Viewed 507552

I would like to remove some data from the workspace. I know the "Clear All" button will remove all data. However, I would like to remove just certain data.

For example, I have these data frames in the data section:

data
data_1
data_2
data_3

I would like to remove data_1, data_2 and data_3, while keeping data.

I tried data_1 <- data_2 <- data_3 <- NULL, which does remove the data (I think), but still keeps it in the workspace area, so it is not fully what I would like to do.

13 Answers
  1. In RStudio, ensure the Environment tab is in Grid (not List) mode.

  2. Tick the object(s) you want to remove from the environment.

  3. Click the broom icon.

You can use the apropos function which is used to find the objects using partial name.

rm(list = apropos("data_"))

Adding one more way, using ls() and remove()

ls() return a vector of character strings giving the names of the objects in the specified environment.

Create a list of objects you want to remove from the environment using ls() and then use remove() to remove it.

remove(list = ls()[ls() !=  "data"])

You can also use tidyverse

# to remove specific objects(s)
rm(list = ls() %>% str_subset("xxx")) 
# or to keep specific object(s)
rm(list = setdiff(ls(), ls() %>% str_subset("xxx")))

Maybe this can help as well

remove(list = c(ls()[!ls() %in% c("what", "to", "keep", "here")] ) )
Related