Saving Files in RStudio

Doug Hemken

June 2020

Like most statistical software, you save the pieces of an R project in several different files.

Scripts

A script and your data are the two most important pieces of a project. With good scripts and your original data, your work is documented and reproducible.

You save scripts pretty much the way you expect. With the script editor as the active window, click File - Save as and give your file a name, along with the file extension “.r”. Although this is just a plain text file, the “.r” file extension will ensure that the software and the operating system recognize this as an R script, later on, enabling the software to work more gracefully.

You can open previously saved scripts from the Files pane (lower right, tabbed with Plots). Just click on the file name.

When you shut down RStudio, any unsaved scripts are automatically saved by default, and reappear when you start up RStudio again.

Data

Save the original data file(s) you started from. Often this will be a text or csv (comma-separated values) file.

Having read your data into R, cleaned it, and created any other data objects (including results objects), you may want to save your intermediate data. This is especially useful if data wrangling or modeling takes a lot of computer time to run.

You can use RStudio to save your Global Environment (the data objects listed in the Environment pane). Click on the Save icon on the Environment toolbar, and give your file a name - RStudio automatically appends an “.RDdata” file extension for you, if you don’t supply it with exactly this capitalization.

Reload saved data by clicking on the file name in the Files pane, or by clicking on the Open icon on the Environment toolbar.

Finally, this can be automated by including the appropriate commands in your scripts, save.image() or save().

Plots

You save plots pretty much as you expect. In the Plots pane, click on Export- Save as Image … on the toolbar. Pick an appropriate image format - the options depend on your computer’s operating system, and which you want depends on how you intend to use the saved image - then give the file a name.

This can also be automated with scripted commands, see help(Devices).

You won’t be able to reopen saved graphics within RStudio.

Text

Surprisingly, RStudio does not make it simple for you to save the contents of the Console. The general idea is that you are usually better off configuring and automating saving your results, and this requires either batch processing (running your script in batch mode) or including some code in your script. We will go more into this, later.

Keep in mind, too, that the Console is limited to the last 1000 lines of text you output.

However, the quick-and-dirty method of saving the Console is to copy- and-paste it into a text file.

These can be reopened later from the Files pane.

To automate saving text output, see sink() or capture.output(). More is in Saving Lots of Output.