7

I tried this command

remove(list = ls())

I expect to clear all R environment (Objects, packages)

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Mohamed SELAMA
  • 86
  • 1
  • 1
  • 4

2 Answers2

14

The simplest and, more importantly, the only reliable way of doing this is to restart R. That takes care of everything.

Just make sure you’re not accidentally saving the current R image when quitting R.

In RStudio, you need to set the option “Save workspace to .RData file on exit” to “Never”, and disable restoring upon restart — this is strongly recommended!

RStudio preferences

After that, make sure that any previously existing .RData files in your project’s folder are deleted (heads up: .RData is an invisible file so you won’t normally see it in a file browser; you can delete it via the command line).

To restart R from within RStudio, you can use “Session” › “Restart R” or Cmd+Shift+F10.

Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
3

The answer was already out there :-) https://stackoverflow.com/a/7506112/7902133

According to this answer, the following code should work

lapply(paste("package:", names(sessionInfo()$otherPkgs), sep=""), 
       detach, 
       character.only = TRUE, 
       unload = TRUE)

You may also want to check the first answer for a full description.

Alfonso
  • 626
  • 6
  • 17
  • 1
    If the question has already an answer elsewhere it should be flagged as duplicate instead of answering it. Please read the FAQ [How should duplicate questions be handled?](http://meta.stackexchange.com/q/10841/): "It's a duplicate. What do I do?; If you have the privilege to vote to close, click the "close" button under the question, select “duplicate of...”, and paste a link to the duplicate question."; "Should I answer it?; No, not if you think it's a duplicate." – Ronak Shah Jul 17 '19 at 09:40
  • 1
    This will not work reliably if there are dependencies between different loaded packages. Even apart from that it might not reliably reset all session state. – Konrad Rudolph Jul 17 '19 at 09:45
  • This "solution" just doesn't answer the original question. – tagoma Sep 23 '21 at 21:26