32

I would like to know if there is any instruction in R that would allow to clean all the variables initialized and to close all the connections open. Just like some sort of Reset function.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Layla
  • 5,234
  • 15
  • 51
  • 66
  • 2
    I seem to recall that there was a discussion of this somewhere (`closeConnection` to close connections, `rm` to remove variables, `detach` to unload packages, something to reset options to their defaults ...) but I can't locate it at the moment. RStudio now has a convenient "restart R" button ... – Ben Bolker Jan 06 '13 at 21:51
  • Note that you would also want to reload all the packages. Somewhere on SO I read that the best way to reset is to restart R. – Josiah Yoder Jul 19 '21 at 20:18
  • And also note that restarting R in R Studio will save your variables and reload them, so in R Studio you would want to clear your variables, then restart R. – Josiah Yoder Jul 19 '21 at 20:19

2 Answers2

61
closeAllConnections()
rm(list=ls())

I hate that second construction since people sometimes sneak it into example code, and when I miss it and copy-paste into my console, and then my entire workspace is wiped out. The real guRus don't make that mistake since they always have multiple emacs windows and always build packages and run code from editing windows and all of those other "wise things to do".

IRTFM
  • 258,963
  • 21
  • 364
  • 487
15

You can use remove() to delete variables. E.g.:

remove('variabl1','variable2','etc')

Not sure about connections, but assume you refer to database connections you opened to load data via e.g. ODBC? I would assume that the package that provides the package also has documentation on how to close a connection (if required or good practise - thus not done automatically).

Jochem
  • 3,295
  • 4
  • 30
  • 55