Restart R in R Studio

  1. The Need to Restart R
  2. Restart R Interactively (Preferred Method)
  3. Restart R in Code (Undocumented)
  4. Use R Projects
  5. References

This article explains the need to restart R and then mentions alternate ways to restart R using R Studio.

The Need to Restart R

When we do any data analysis, we must ensure that our results depend only on the data we use for the analysis.

However, by default, R Studio gives us one common R process and a common global environment for all the files that are open in R Studio. If we create a variable with the same name in multiple documents, the one created last overwrites the previous one.

If we go back to the first document and use the variable, we get its new value created in the second document.

To load all required libraries and create all variables in the current document, we need to restart R when starting work on a new document or switching back to a document.

Restarting R will clear all variables and unload all our loaded libraries.

An additional benefit of restarting R is that it frees R’s computer memory, which is no longer in use.

Restart R Interactively (Preferred Method)

Within R Studio, we can restart R using either the menu item or its keyboard shortcut.

  1. Click Session > Restart R.
  2. Press Ctrl+Shift+F10. On Mac, press Command in place of Ctrl.

This is the only documented way to restart R from the R Studio IDE.

Restart R in Code (Undocumented)

An undocumented way to restart R in R Studio mentioned in online forums/articles is using the code .rs.restartR().

However, this neither unloads packages nor clears the variables that were created.

Since it is undocumented, it is better to avoid using this method.

Use R Projects

Since one of the reasons to restart R is to start data analysis in a clean R session, a good approach is to use R Projects. R Studio creates a separate R session for each project.

References

See Chapter 8 of R for Data Science to learn more about R Projects.

Also, see Section 1.6 of R for Health Data Science to learn about startup options for R Studio.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.