A.4 First R Script

Let’s open Rstudio and perform the following steps:

1. Create a New Project where we will store all the scripts related to this book. Click FileNew Project and then choose to start in a brand new working directory, in any location you like. Choose New Project as the project type.

From now on, we are assuming that the project name is LMLCR and the project has been opened. All source files we create will be relative to the project directory.

2. Create a new R source file, FileNew FileR Script. Save the file as, for example, sandbox_01.R.

The source editor (top left pane) behaves just like any other text editor. Standard keyboard shortcuts are available, such as CTRL+C and CTRL+V (Cmd+C and Cmd+V on MacOS) for copy and paste, respectively.

A list of keyboard shortcuts is available at https://support.rstudio.com/hc/en-us/articles/200711853-Keyboard-Shortcuts

3. Input the following R code into the editor:

# My first R script
# This is a comment

# Another comment

# Everything from '#' to the end of the line
#     is ignored by the R interpreter
print("Hello world") # prints a given character string
print(2+2) # evaluates the expression and prints the result
x <- seq(0, 10, length.out=100) # a new numeric vector
y <- x^2 # squares every element in x
plot(x, y, las=1, type="l") # plots y as a function of x
4. Execute the 5 above commands, line by line, by positioning the keyboard cursor accordingly and pressing Ctrl+Enter (Cmd+Return on MacOS).

Each time, the command will be copied to the console (bottom-left pane) and evaluated.

The last line generates a nice plot which will appear in the bottom-right pane.

While you learn, we recommend that, you get used to writing your code in an R script and executing it just as we did above.

On a side note, You can execute (source) the whole script by pressing Ctrl+Shift+S (Cmd+Shift+S on MacOS).