Removing Files from Global Environment with a Certain Pattern

Viewed 34

I have these files in my global environment:

 x <- sapply(sapply(ls(), get), is.data.frame)
 n = names(x)[(x==TRUE)] 

 n

 [1] "sample_1"  "sample_10" "sample_2"  "sample_3"  "sample_4"  "sample_5"  "sample_6"  "sample_7"  "sample_8"  "sample_9"  "table_i"  

I want to remove all files that start with "samp". I found the this code that can do this (How do I clear only a few specific objects from the workspace?):

rm(list = apropos("samp_"))

Now, I want to learn how to do the same thing using a different way. I found another way to find out all files in the global environment that start with "samp":

 nn = grep("samp", n, value = TRUE)  

 [1] "sample_1"  "sample_10" "sample_2"  "sample_3"  "sample_4"  "sample_5"  "sample_6"  "sample_7"  "sample_8"  "sample_9" 

Then, I tried to delete these files:

for (file in nn){
    nn[i] <- NULL
  }

do.call(file.remove, list(nn))
  • I think I am missing something here - can someone please show me how to correct this?

Thank you!

1 Answers

You can make use of pattern inside of the remove function:

rm(list = ls(pattern = "^samp"))

Or using grep:

rm(list = grep("^samp", ls(), value = TRUE))
Related