Getting familiar with the working environment: Getting familiar with the R interface
Creating and saving R scripts
Opening or creating a script in RStudio is a fundamental step in the R programming process. A script is a plain text file that contains R code and commands, and allows you to organise and execute your code in a structured manner. A script is fundamental to programming because it allows you to organise your R code logically and to create a record of the steps taken in your analysis or computation. This makes your analysis reproducible, allows sharing with others, documentation and collaboration. In addition, you can execute entire scripts or only parts of it to perform automated execution operations, which save you time and effort.
Let's see how you can open a new or existing script and how you can save it to be re-used later.
Creating a new R script To create a new R script, go to the upper-left corner of the RStudio interface and select the menu item File > New File > R Script. Alternatively, you can use the keyboard shortcut Ctrl + Shift + N
(MS Windows) or Cmd + Shift + N
(macOS) to create a new script.
Loading an existing R script If you already have an R script that you want to open, select RStudio menu item File > Open File. Browse your file system to locate the R script, select it, and click on the Open button.
Viewing and editing the R scriptOnce the script is opened, you will see the content in the Source Editor panel, which is the central area of RStudio. Here, you can view and edit the R code.
Saving the R script Once you have written or edited your R code in the Source Editor panel, you might want to save it for future use. To do so, go to the top-left corner of the RStudio interface and click on File. From the drop-down menu, select Save or Save As. If you select Save As, a window will open, allowing you to choose the location and provide a name for your script. Navigate to the desired folder, name your script (with a sensible name), and click on Save. If you had selected Save in the drop-down menu, RStudio will save the changes to the existing file without prompting for a location or filename. When saving your R script, RStudio will automatically add the .R
file extension to the filename. For example, if you save your script with the name my_analysis, RStudio will save it as my_analysis.R.
RStudio also provides the usual keyboard shortcuts to save your script quickly:
- Save:
Ctrl + S
(MS Windows) orCmd + S
(macOS). - Save As:
Ctrl + Shift + S
(Windows) orCmd + Shift + S
(macOS).
By default, RStudio will prompt you to save new scripts in your working directory (see next theory page). The working directory is the folder where RStudio will look for files and data unless specified otherwise. If you want to save your script in a specific folder, use Save As and navigate to the desired location.
Saving your R script regularly is essential to preserve your work and avoid losing any changes you've made.