Part 1: Introduction to R

Overview

Teaching: 15 min
Exercises: 10 min
Questions
  • What data types are available in R?

  • What is an object?

  • How can values be initially assigned to variables of different data types?

  • What arithmetic and logical operators can be used?

  • How can subsets be extracted from vectors and data frames?

  • How does R treat missing values?

  • How can we deal with missing values in R?

Objectives
  • Define the following terms as they relate to R: object, assign, call, function, arguments, options.

  • Assign values to objects in R.

  • Learn how to name objects.

  • Use comments to inform script.

  • Solve simple arithmetic operations in R.

  • Call functions and use arguments to change their default options.

  • Inspect the content of vectors and manipulate their content.

  • Subset and extract values from vectors.

  • Analyze vectors with missing data.

Creating objects in R

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

3 + 5
[1] 8
12 / 7
[1] 1.714286

However, to do useful and interesting things, we need to assign values to objects. To create an object, we need to give it a name followed by the assignment operator <-, and the value we want to give it:

task_score <- 1.0

<- 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 + - (push Option at the same time as the - key) does the same in a Mac.

Objects can be given any name such as x, total_scores, or subject_id. You want your object names to be explicit and not too long. They cannot start with a number (2x is not valid, but x2 is). R is case sensitive (e.g., age is different from Age). There are some names that cannot be used because they are the names of fundamental functions in R (e.g., if, else, for, see here for a complete list). In general, even if it’s allowed, it’s best to not use other function names (e.g., c, T, mean, data, df, weights). If in doubt, check the help to see if the name is already in use. It’s also best to avoid dots (.) within an object name as in my.dataset. There are many functions in R with dots in their names for historical reasons, but because dots have a special meaning in R (for methods) and other programming languages, it’s best to avoid them. It is also recommended to use nouns for object names, and verbs for function names. It’s important to be consistent in the styling of your code (where you put spaces, how you name objects, etc.). Using a consistent coding style makes your code clearer to read for your future self and your collaborators. In R, three popular style guides are Google’s, Jean Fan’s and the tidyverse’s. The tidyverse’s is very comprehensive and may seem overwhelming at first. You can install the lintr package to automatically check for issues in the styling of your code.

Objects vs. variables

What are known as objects in R are known as variables in many other programming languages. Depending on the context, object and variable can have drastically different meanings. However, in this lesson, the two words are used synonymously. For more information see: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects

When assigning a value to an object, R does not print anything. You can force R to print the value by using parentheses or by typing the object name:

task_score <- 5.0    # doesn't print anything
(task_score <- 5.0)  # putting parenthesis around the call prints the value of `task_score`
[1] 5
task_score         # and so does typing the name of the object
[1] 5

Now that R has task_score in memory, we can do arithmetic with it. For instance, we may want to scale it to a larger number:

10 * task_score
[1] 50

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

task_score <- 2.5
10 * task_score
[1] 25

This means that assigning a value to one object does not change the values of other objects For example, let’s store the scaled score in a new object, scaled_task_score:

scaled_score <- 10 * task_score

and then change scaled_task_score to 50.

task_score <- 50

Exercise

What do you think is the current content of the object scaled_score? 2.5, 25, or 500?

Solution

The value of task_score is still 2.5 because you have not re-run the line scaled_score <- 10 * task_score since changing the value of task_score.

Comments

All programming languages allow the programmer to include comments in their code. To do this in R we use the # character. Anything to the right of the # sign and up to the end of the line is treated as a comment and is ignored by R. You can start lines with comments or include them after any code on the line.

task_score <- 5.0			# raw score on a task
scaled_score <- task_score * 10	# scale the raw score by 10
scaled_score				# print the scaled score
[1] 50

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.

Exercise

Create two variables speaking_score and writing_score and assign them values. It should be noted that R Studio might add “()” after width and if you leave the parentheses you will get unexpected results. This is why you might see other programmers abbreviate common words. Create a third variable productive_score and give it a value based on the current values of speaking_score and writing_score. Show that changing the values of either speaking_score and writing_score does not affect the value of productive_score.

Solution

speaking_score <- 2.5
writing_score <- 3.5
productive_score <- speaking_score + writing_score
productive_score
[1] 6
# change the values of speaking_score and writing_score
speaking_score <- 7.0
writing_score <- 6.5
# the value of productive_score isn't changed
productive_score
[1] 6

Functions and their arguments

Functions are “canned scripts” that automate more complicated sets of commands including operations assignments, etc. Many functions are predefined, or can be made available by importing R packages (more on that later). A function usually gets 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 (in fact, the output) 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 dataset. We’ll see that when we read data files into R.

Arguments can be anything, not only numbers or filenames, but also other objects. Exactly what each argument means differs per function, and must be looked up in the documentation (see below). 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 want more digits we can see how to do that by getting information about the round function. We can use args(round) or look at the help for this function using ?round.

args(round)
function (x, digits = 0) 
NULL
?round

We see that if we want a different number of digits, we can type digits=2 or however many we want.

round(3.14159, digits = 2)
[1] 3.14

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)
[1] 3.14

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

round(digits = 2, x = 3.14159)
[1] 3.14

It’s good practice to put the non-optional arguments (like the number you’re rounding) first in your function call, and to 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.

Exercise

Type in ?round at the console and then look at the output in the Help pane. What other functions exist that are similar to round? How do you use the digits parameter in the round function?

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 scores for speaking tasks and assign it to a new object speak_task:

speak_task <- c(3, 7, 10, 6)
speak_task
[1]  3  7 10  6

A vector can also contain characters. For example, we can have a vector of demographic information from our test takers such as first language (first_language):

first_language <- c("Arabic", "Bengali", "Mandarin", "Portuguese")
first_language
[1] "Arabic"     "Bengali"    "Mandarin"   "Portuguese"

The quotes around “Mandarin”, etc. are essential here. Without the quotes R will assume there are objects called Arabic, Bengali, Mandarin and Portuguese. 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(speak_task)
[1] 4
length(first_language)
[1] 4

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(speak_task)
[1] "numeric"
class(first_language)
[1] "character"

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(speak_task)
 num [1:4] 3 7 10 6
str(first_language)
 chr [1:4] "Arabic" "Bengali" "Mandarin" "Portuguese"

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 4 atomic vector types are:

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).

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:

first_language <- c("Arabic", "Bengali", "Mandarin", "Portuguese")
first_language[2]
[1] "Bengali"
first_language[c(3, 2)]
[1] "Mandarin" "Bengali" 

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

more_first_language <- first_language[c(1, 2, 3, 2, 1, 3)]
more_first_language
[1] "Arabic"   "Bengali"  "Mandarin" "Bengali"  "Arabic"   "Mandarin"

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

Typically, these logical subsetting is 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 5:

speak_task > 5    # will return logicals with TRUE for the indices that meet the condition
[1] FALSE  TRUE  TRUE  TRUE
## so we can use this to select only the values above 5
speak_task[speak_task > 5]
[1]  7 10  6

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

speak_task[speak_task <= 3 | speak_task > 7]
[1]  3 10
speak_task[speak_task >= 7 & speak_task >= 3]
[1]  7 10

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 <-).

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:

country <- c("Egypt", "Bangladesh", "China", "Brazil")
country[country == "Bangladesh" | country == "Brazil"] # returns both Bangladesh and Brazil
[1] "Bangladesh" "Brazil"    
country %in% c("Bangladesh", "China", "Brazil", "USA", "Canada")
[1] FALSE  TRUE  TRUE  TRUE
country[country %in% c("Bangladesh", "China", "Brazil", "USA", "Canada")]
[1] "Bangladesh" "China"      "Brazil"    

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.

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.

total_scores <- c(50, 75, 64, NA, 91)
mean(total_scores)
[1] NA
max(total_scores)
[1] NA
mean(total_scores, na.rm = TRUE)
[1] 70
max(total_scores, na.rm = TRUE)
[1] 91

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.
total_scores[!is.na(total_scores)]
[1] 50 75 64 91
## Returns the object with incomplete cases removed. The returned object is an atomic vector of type `"numeric"` (or `"double"`).
na.omit(total_scores)
[1] 50 75 64 91
attr(,"na.action")
[1] 4
attr(,"class")
[1] "omit"
## Extract those elements which are complete cases. The returned object is an atomic vector of type `"numeric"` (or `"double"`).
total_scores[complete.cases(total_scores)]
[1] 50 75 64 91

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

Exercise

  1. Using this vector of total_scores, create a new vector with the NAs removed.

     total_scores <- c(15, 72, 91, 77, NA, 36, 41, 33, 82, 86, 71, 88, 73, 61, NA, 94)
    
  2. Use the function median() to calculate the median of the total_scores vector.

  3. Use R to figure out how many people score above 70.

Solution

total_scores <- c(15, 72, 91, 77, NA, 36, 41, 33, 82, 86, 71, 88, 73, 61, NA, 94)
total_scores_no_na <- total_scores[!is.na(total_scores)]
# or
total_scores_no_na <- na.omit(total_scores)
# 2.
median(total_scores, na.rm = TRUE)
[1] 72.5
# 3.
total_scores_above_70 <- total_scores_no_na[total_scores_no_na > 70]
length(total_scores_above_70)
[1] 9

Now that we have learned how to write scripts, and the basics of R’s data structures, we are ready to start working with the a dataset of test scores, and learn about data frames.

Key Points

  • Access individual values by location using [].

  • Access arbitrary sets of data using [c(...)].

  • Use logical operations and logical vectors to access subsets of data.