2

I often like to clear all variables using rm(list = ls()) so that I can run a script from scratch; however, this command removes all objects, regardless of type.

I want to preserve all variables listed under 'Functions' in RStudio whilst removing everything else.

I ask because I have two functions in my environment which I would like to preserve, but I also don't want to have to manually type out rm(var1, var2, df1, df2, ...) each time I want to remove all variables whilst preserving the 'Functions'.

How can this be done?

Mus
  • 7,290
  • 24
  • 86
  • 130
  • Maybe could this help you to classify your environment objects so you can create a specific list to remove `sapply(ls(), function(x) typeof(get(x)))` – Yacine Hajji Mar 04 '22 at 15:42
  • I've updated the question to make it clearer (current security settings won't allow me to upload an image/screenshot). – Mus Mar 04 '22 at 15:42
  • https://stackoverflow.com/questions/30767667/remove-all-objects-of-a-given-type-in-r may help – user63230 Mar 04 '22 at 15:48

1 Answers1

2

In RStudio, the Data items seems to be referring to data.frame/tibble/data.table objects. If that is the case, get the object names that data.frame and rm them

rm(list = ls()[sapply(ls(), \(x) inherits(get(x), 
          what = c("data.frame", "list")))])

Or may use eapply

rm(list = names(which(unlist(eapply(.GlobalEnv, \(x) 
     inherits(x, what = c("data.frame", "list")))))))

Update

Based on the OP's comments, if it is to only everything except functions

rm(list = names(which(!unlist(eapply(.GlobalEnv, 
    \(x) inherits(x, what = "function"))))))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • This is very close, but it still leaves two objects (in my case, it leaves a connection object and also a list). I essentially want to remove absolutely everything except for the functions that I have already created. – Mus Mar 04 '22 at 15:44
  • I want to remove absolutely everything except for functions. – Mus Mar 04 '22 at 15:48
  • 1
    Yes, I appear to have made an error in my wording. I will change it. – Mus Mar 04 '22 at 15:57
  • I've spotted an error - your answer states that I wish to remove all functions whereas I said I wanted to _keep_ all functions. I modified the `=` to `!=` but that failed. Also, somebody else posted a solution of `rm(list = ls()[sapply(ls(), function(i) class(get(i))) != "function"])` (now deleted for some reason) which works. – Mus Mar 07 '22 at 13:27
  • 1
    @Mus sorry, that was a mistake. I updated. You need the `!` before `unlist` – akrun Mar 07 '22 at 15:34