Writing and annotating R code

This lesson is derived from Data Carpentry teaching materials available under the CC BY 4.0 license:

https://datacarpentry.org/R-ecology-lesson/

Objectives:

  • Be able to create and manipulate objects

  • Know how to annotate your code

  • Understand how functions work

  • Have a working knowledge of vectors and different data types

  • Be aware of ways to handle missing values in vectors

1. Creating objects

You can get output from R simply by typing calculations in the console:

3 + 5
12 / 7
2 ^ 5

Code without spaces (e.g. 1+1) also works, although long sections of code without spaces can be difficult to read. For decimal points, R accepts the full stop symbol (.) instead of a comma (,).

To do useful and interesting things in R, we can assign values to objects. To create an object, we give it a name followed by the assignment operator <-, and a value. Let’s take an animal’s weight as an example:

weight_kg <- 55

<- is the assignment operator. It assigns values on the right to objects on the left. So, after executing x <- 3, the value of x is 3. The arrow can be read as 3 goes into x. For historical reasons, you can also use = for assignments, but not in every context. Because of the slight differences in syntax, it is good practice to always use <- for assignments.

In RStudio, typing Alt + - (push Alt at the same time as the - key) will write <- in a single keystroke in a PC, while typing Option + - does the same in a Mac.

Note: While previously we could immediately see the result of a calculation, when using objects the result is not immediately visible. We can access the output by running weight_kg on its own:

weight_kg

Now that R has weight_kg in memory, we can do arithmetic with it. For instance, we may want to convert this weight into pounds (weight in pounds is 2.2 times the weight in kg):

2.2 * weight_kg

We can also change an object’s value by assigning it a new one:

weight_kg <- 57.5
2.2 * weight_kg

This means that assigning a value to one object does not change the values of other objects For example, let’s store the animal’s weight in pounds in a new object, weight_lb:

weight_lb <- 2.2 * weight_kg

and then change weight_kg to 100.

weight_kg <- 100

What do you think is the current content of the object weight_lb?

126.5 or 220?

2. Removing objects

Sometimes we need to remove an object from the workspace. This can be done using rm() (for example, rm(weight_kg) would remove weight_kg).

There is also a command for completely clearing your workspace: rm(list = ls()). This deletes all objects currently in R’s memory. Use this command with caution - there is no ‘Undo’ button in R. If you accidentally remove something, you will need to run your code again!

3. Code annotation

The comment character in R is #, anything to the right of a # in a script will be ignored by R. It is useful to leave notes and explanations in your scripts. RStudio makes it easy to comment or uncomment a paragraph: after selecting the lines you want to comment, press at the same time on your keyboard Ctrl + Shift + C. If you only want to comment out one line, you can put the cursor at any location of that line (i.e. no need to select the whole line), then press Ctrl + Shift + C.

4. Object naming guidelines

The following guidelines are useful to keep in mind when naming new objects:

  • The name must begin with a letter.
  • It can contain numbers, full stops and underscores, and is case-sensitive.
  • While it is possible to include spaces in object names, this requires extra effort and is not recommended.
    • In general, it is good practice to keep your code as simple and easy to read as possible.
  • Letters with umlauts and accents (e.g. special letters in the Finnish and Spanish alphabet) are best to avoid.
    • They may not work on all systems, which can become problematic when sharing your code with others.

Challenge:

At this point, let’s complete Basic Features Exercise Block 1 (see separate exercise sheet on eLena) (~ 10 mins).

5. Functions and their arguments

Functions are “canned scripts” that automate more complicated sets of commands including operations and assignments etc. Many functions are predefined, or can be made available by importing R packages (more on that later).

A function usually takes one or more inputs called arguments. Functions often (but not always) return a value. A typical example would be the function sqrt(). The input (the argument) must be a number, and the return value is the square root of that number. Executing a function (‘running it’) is called calling the function. An example of a function call is:

b <- sqrt(a)

Here, the value of a is given to the sqrt() function, the sqrt() function calculates the square root, and returns the value which is then assigned to the object b. This function is very simple, because it takes just one argument.

The return ‘value’ of a function need not be numerical (like that of sqrt()), and it also does not need to be a single item: it can be a set of things, or even a data set. We’ll see that when we read data files into R.

Arguments can be anything, not only numbers or file names, but also other objects. Exactly what each argument means depends on the function, and must be looked up in the documentation (more on that in a separate lesson).

Some functions take arguments which may either be specified by the user, or, if left out, take on a default value: these are called options. Options are typically used to alter the way the function operates, such as whether it ignores ‘bad values’, or what symbol to use in a plot. However, if you want something specific, you can specify a value of your choice which will be used instead of the default.

Let’s try a function that can take multiple arguments: round().

round(3.14159)
#> [1] 3

Here, we’ve called round() with just one argument, 3.14159, and it has returned the value 3. That’s because the default is to round to the nearest whole number.

If we wanted more digits but didn’t know to achieve that, we could have a closer look at the round function using the command ?round . Since we’ll go into more detail on help files later, right now it’s enough for us to know that we can specify the function digits inside round:

round(3.14159, digits = 2) # rounding to two digits

# the default definition for the round function is:
function(x, digits = 0) 

If you provide the arguments in the exact same order as they are defined you don’t have to name them:

round(3.14159, 2)

And if you do name the arguments, you can switch their order:

round(digits = 2, x = 3.14159)

It’s good practice to put the non-optional arguments (like the number you’re rounding) first in your function call, and to then specify the names of all optional arguments. If you don’t, someone reading your code might have to look up the definition of a function with unfamiliar arguments to understand what you’re doing.

6. Vectors and data types

A vector is the most common and basic data type in R, and is pretty much the workhorse of R. A vector is composed by a series of values, which can be either numbers or characters. We can assign a series of values to a vector using the c() function. For example we can create a vector of animal weights and assign it to a new object weight_g:

weight_g <- c(50, 60, 65, 82)
weight_g

A vector can also contain characters:

animals <- c("mouse", "rat", "dog")
animals

The quotes around “mouse”, “rat”, etc. are essential here. Without the quotes R will assume objects have been created called mouse, rat and dog. As these objects don’t exist in R’s memory, there will be an error message.

There are many functions that allow you to inspect the content of a vector. length() tells you how many elements are in a particular vector:

length(weight_g)
length(animals)

An important feature of a vector, is that all of the elements are the same type of data. The function class() indicates the class (the type of element) of an object:

class(weight_g)
class(animals)

The function str() provides an overview of the structure of an object and its elements. It is a useful function when working with large and complex objects:

str(weight_g)
str(animals)

You can use the c() function to add other elements to your vector:

weight_g <- c(weight_g, 90) # add to the end of the vector
weight_g <- c(30, weight_g) # add to the beginning of the vector
weight_g

In the first line, we take the original vector weight_g, add the value 90 to the end of it, and save the result back into weight_g. Then we add the value 30 to the beginning, again saving the result back into weight_g.

We can do this over and over again to grow a vector, or assemble a dataset. As we program, this may be useful to add results that we are collecting or calculating.

An atomic vector is the simplest R data type and is a linear vector of a single type. Above, we saw 2 of the 6 main atomic vector types that R uses: "character" and "numeric" (or "double"). These are the basic building blocks that all R objects are built from. The other four atomic vector types are:

  • "logical" for TRUE and FALSE (the boolean data type)
  • "integer" for integer numbers (e.g., 2L, the L indicates to R that it’s an integer)
  • "complex" to represent complex numbers with real and imaginary parts (e.g. 1 + 4i)
  • "raw" for bitstreams
    • The last two are less common and we won’t cover those here.

You can check the type of your vector using the typeof() function and inputting your vector as the argument.

Vectors are one of the many data structures that R uses. Other important ones are lists (list), matrices (matrix), data frames (data.frame), factors (factor) and arrays (array).

In this workshop, we will be spending lots of time with data frames, arguably the most important data structure in R (more on that later!).

Challenge:

At this point, let’s complete Basic Features Exercise Block 2 (~ 15 mins).

7. Subsetting vectors

If we want to extract one or several values from a vector, we must provide one or several indices in square brackets. For instance:

animals <- c("mouse", "rat", "dog", "cat")
animals[2]

#> [1] "rat"
animals[c(3, 2)]
#> [1] "dog" "rat"

We can also repeat the indices to create an object with more elements than the original one:

more_animals <- animals[c(1, 2, 3, 2, 1, 4)]
more_animals

#> [1] "mouse" "rat" "dog" "rat" "mouse" "cat"

R indices start at 1. Programming languages like Fortran, MATLAB, Julia, and R start counting at 1, because that’s what human beings typically do. Languages in the C family (including C++, Java, Perl, and Python) count from 0 because that’s simpler for computers to do.

Conditional subsetting

Another common way of subsetting is by using a logical vector. TRUE will select the element with the same index, while FALSE will not:

weight_g <- c(21, 34, 39, 54, 55)
weight_g[c(TRUE, FALSE, TRUE, TRUE, FALSE)]

#> [1] 21 39 54

Typically, these logical vectors are not typed by hand, but are the output of other functions or logical tests. For instance, if you wanted to select only the values above 50:

weight_g > 50    

# will return logicals with TRUE for the indices that meet the condition

#> [1] FALSE FALSE FALSE  TRUE  TRUE

# so we can use this to select only the values above 50
weight_g[weight_g > 50]

#> [1] 54 55

You can combine multiple tests using & (both conditions are true, AND) or | (at least one of the conditions is true, OR):

weight_g[weight_g < 30 | weight_g > 50]

#> [1] 21 54 55

How about if we try:

weight_g[weight_g >= 30 & weight_g == 21]

#> numeric(0)

Here, < stands for “less than”, > for “greater than”, >= for “greater than or equal to”, and == for “equal to”. The double equal sign == is a test for numerical equality between the left and right hand sides, and should not be confused with the single = sign, which performs variable assignment (similar to <-).

Here is a useful summary of possible comparisons and operators:

## different comparisons:
# less than `<`
# greater than `>`
# less or equal `<=`
# greater or equal `>=`
# equal to `==`
# not equal to `!=`

## logical operators:
# and `&`
# or `|`
# not `!` 

A common task is to search for certain strings in a vector. One could use the “or” operator | to test for equality to multiple values, but this can quickly become tedious. The function %in% allows you to test if any of the elements of a search vector are found:

animals <- c("mouse", "rat", "dog", "cat")
animals[animals == "cat" | animals == "rat"] 
# returns both rat and cat

animals %in% c("rat", "cat", "dog", "duck", "goat")
#> [1] FALSE  TRUE  TRUE  TRUE

animals[animals %in% c("rat", "cat", "dog", "duck", "goat")]
#> [1] "rat" "dog" "cat"

Optional challenge: Can you figure out why "four" > "five" returns TRUE?

8. Missing data

As R was designed to analyze datasets, it includes the concept of missing data (which is uncommon in other programming languages). Missing data are represented in vectors as NA (Not Available).

When doing operations on numbers, most functions will return NA if the data you are working with include missing values. This feature makes it harder to overlook the cases where you are dealing with missing data. You can add the argument na.rm = TRUE to calculate the result while ignoring the missing values.

heights <- c(2, 4, 4, NA, 6)
mean(heights)
max(heights)

mean(heights, na.rm = TRUE)
max(heights, na.rm = TRUE)

If your data include missing values, you may want to become familiar with the functions is.na(), na.omit(), and complete.cases(). See below for examples.

# Extract those elements which are not missing values.
heights[!is.na(heights)]

# Returns the object with incomplete cases removed. The returned object is an atomic vector of type `"numeric"` (or `"double"`).
na.omit(heights)

# Extract those elements which are complete cases. The returned object is an atomic vector of type `"numeric"` (or `"double"`).
heights[complete.cases(heights)]

Recall that you can use the typeof() function to find the type of your atomic vector.

Challenge:

At this point, let’s complete Basic Features Exercise Block 3 (~ 10 mins).