4  Your first R script

-

Opening, Running and Saving a Code Script in RStudio

Let’s write and run our first line of code in RStudio.

Opening a Code Script

When opening RStudio you should see the three main windows

Start by opening a new R script (in RStudio). To do so, click on “File” in the top left menu bar, then select “New File” and choose “R Script”. This will open an empty script file in the “Source” panel.

Running a Code Script

In the script file, you can write your R code. Type your code directly into the script file. R scripts are essentially a collection of commands and functions that are executed in a sequential manner.

To run a line of code in your R script, you can either use

  • press CTRL+ENTER or
  • click on the “Run” button in RStudio (top right)

This will run the code in the script and display the output in the console.

Remember to have your cursor anywhere on the line you want to run the code, and then use CTRL+ENTER or click on Run to execute the code.


Type in your script window (top left window) and run

2+2
[1] 4

After running your code, the output will be displayed in the Console panel (bottom left panel). If there are any errors or warnings, they will also be shown here.

If you created any object, you can view it in the Environment/History panel (top right panel).

Type and run

x = 2+2

You should be able to see the object x in your Environment panel.

Saving a Code Script

After writing your code and running it successfully, it is time to save your code. To save your code script in RStudio, go to “File” > “Save”. Refer to the previous section on workflow to name your code efficiently.


You are now ready to learn R