6  Write And Execute Code

6.1 Console Window

Single lines of code can be written in the console window (bottom left RStudio pane). However, code written in the console window is not saved and difficult to use for multiple lines of interrelated code. Consequently, the console is best used for experimenting with single lines of code, accessing help files, installing packages, and other simple tasks that are unnecessary to document for reproducibility.

  1. Type getwd() in the console and hit return. A file path to the current R Project is returned.

  2. Type install.packages(“beepr”)

  3. Type ?beepr in the console and hit return. A help document for the beepr package will appear in the bottom right panel of RStudio.

  4. Experiment with beepr() using values 1 through 10.

  5. Press the up arrow to cycle through previous codes executed in the console window. Hit enter to run any code that reappears.

6.2 Writing code inline with text.

R code can be mixed in with R Markdown text by surrounding the code with backticks and preceding code with the letter r, like this: `r 2+3`. Rendering replaces inline code with output and is often used for reporting values.

In Markdown space type `r 2+3`. Place the cursor inside the backtick marks and press “command/control + enter” to see a preview of the executed code.

6.3 Writing code inside code chunks

Placing multiple lines of code that work together inside code chunks is usually superior to writing inline code. Commands inside code chunk can be executed individually using the shortcut keys “command/control + enter” or collectively using “shift + command/control + enter”.

6.4 Executing code & code chunks

Below are several ways to execute the commands in code chunks:

  1. Execute the entire code chunk. Press “shift + Command + Enter” or click the green arrow at the top right of the code chunk.
  2. Execute a single line. With the cursor anywhere on a line of code, press “command/control + Enter”.
  3. Execute all code chunks above a code chunk. Click the icon to the left of the green arrow at the right of a code chunk.
  4. Execute all code chunks. Press “Command + Option + R” or select this option from the “Run” pull-down menu.

Recreate the code chunks below and experiment with the above approaches. Any visible output will appear in the console window and possibly below the code chunk, depending on RStudio settings.

Code
print("Hello World")
x <- -10:10
y <- x^2
tb <- tibble(x, y)
tb
Code
summary(tb)
hist(mtcars$hp)
Code
# mtcars is a dataset that comes with R
data(mtcars) 
head(mtcars) 
str(mtcars) 
names(mtcars) 
rownames(mtcars) 

6.5 Assignment

Commands that use the assignment operator, <-, commit objects to memory. Objects in memory are visible in the Environment panel (upper right) under “Data” (dataframes and lists) or “Values” (vectors).

6.6 Comments vs Headers

Hashtags inside code chunks tell R to ignore the following text, which is called a comment. Comments provide short explanatory messages of code, as shown below.

Code
# Create a mind-blowing scatter plot using base R
x <- -10:10
y <- x^2
plot(x,y)

6.7 Commands and arguments

In general, commands perform actions on data. Everything passed into the parentheses of a command is an argument. Commas separate multiple arguments. The first command below, data(), has one argument, while the head() command has two.

Code
data(mtcars)
head(mtcars, 4)
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710     22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1

6.7.1 Argument names

The plot commands below has two arguments that identify the plotted data. Arguments may have optional names, such as x = and y = in the plot command. Including the names of arguments improves readability but can be avoided if the arguments are presented in the exact order a command expects.

Code
# with names
plot(x = mtcars$wt, y = mtcars$mpg) 

# without names
plot(mtcars$wt, mtcars$mpg) 

6.8 Pipe with %>% or |>

The Tidyverse pipe operator, %>%, allows code to follow a natural reading pattern, left to right and top to bottom. The %>% operator takes the output of code left of the operator and passes that into the first argument of a command on the right.

R version 4.1 added a native pipe operator, |>. As of version 4.2 though, the native pipe operator lacked some functionality compared to %>%. Users can choose their preferred pipe operator from Tools > Global Options > Code menu.

Below are examples of the pipe operator in use. The example 1 line of code would read “start with mtcars, select the hp column, then show a summary of the values.” Example 2 would read “start with the vector called y, take the absolute value of all elements, then take the square root of all elements, then round all elements to two decimal places, then take the mean of all values.”

Code
# example 1
mtcars %>% select(hp) %>% summary
       hp       
 Min.   : 52.0  
 1st Qu.: 96.5  
 Median :123.0  
 Mean   :146.7  
 3rd Qu.:180.0  
 Max.   :335.0  
Code
# example 2
y %>% abs %>% sqrt %>% round(2) %>% mean
[1] 5.238095

6.9 Nesting commands (not piping)

Equivalent lines of code without piping are below. Command execution begins with the innermost nested command and proceeds outwardly. The inside-out order makes code challenging to read and write.

Code
# example 1
summary(select(mtcars, hp))
       hp       
 Min.   : 52.0  
 1st Qu.: 96.5  
 Median :123.0  
 Mean   :146.7  
 3rd Qu.:180.0  
 Max.   :335.0  
Code
# example 2
mean(round(sqrt(abs(y)), 2))
[1] 5.238095