Using R

Overview

Teaching: 50 min
Exercises: 15 min
Questions
  • What can R do?

  • How can I install new packages?

Objectives
  • Define a variable

  • Assign data to a variable

  • Manage a workspace in an interactive R session

  • Use mathematical and comparison operators

  • Call functions

  • Manage packages

Using R as a calculator

The simplest thing you could do with R is do arithmetic: Open an R script, save it, and type in the following:

1 + 100
[1] 101

Send this command to the R console to be executed with Ctrl+Return.

And R will print out the answer, with a preceding “[1]”. Don’t worry about this for now, we’ll explain that later. For now think of it as indicating output.

And R will print out the answer, with a preceding “[1]”. Don’t worry about this for now, we’ll explain that later. For now think of it as indicating output.

What happens if your command is incomplete? Try writing this in a script and running it with Ctrl+Return:

> 1 +
+

Any time you hit return and the R session shows a “+” instead of a “>”, it means it’s waiting for you to complete the command. If you want to cancel a command you can simply hit Esc and RStudio will give you back the “>” prompt.

Tip: Cancelling commands

You can also cancel commands using Ctrl+C instead of Esc. This applies to Mac users as well!

Cancelling a command isn’t only useful for killing incomplete commands: you can also use it to tell R to stop running code (for example if it’s taking much longer than you expect).

When using R as a calculator, the order of operations is the same as you would have learned back in school.

From highest to lowest precedence:

3 + 5 * 2
[1] 13

Use parentheses to group operations in order to force the order of evaluation if it differs from the default, or to make clear what you intend.

(3 + 5) * 2
[1] 16

This can get unwieldy when not needed, but clarifies your intentions. Remember that others may later read your code.

(3 + (5 * (2 ^ 2))) # hard to read
3 + 5 * 2 ^ 2       # clear, if you remember the rules
3 + 5 * (2 ^ 2)     # if you forget some rules, this might help

The text after each line of code is called a “comment”. Anything that follows after the hash (or octothorpe) symbol # is ignored by R when it executes code.

Really small or large numbers get a scientific notation:

2/10000
[1] 2e-04

Which is shorthand for “multiplied by 10^XX”. So 2e-4 is shorthand for 2 * 10^(-4).

You can write numbers in scientific notation too:

5e3  # Note the lack of minus here
[1] 5000

Comparing things

We can also do comparison in R:

1 == 1  # equality (note two equals signs, read as "is equal to")
[1] TRUE
1 != 2  # inequality (read as "is not equal to")
[1] TRUE
1 < 2  # less than
[1] TRUE
1 <= 1  # less than or equal to
[1] TRUE
1 >= -9 # greater than or equal to
[1] TRUE

Tip: Comparing Numbers

Try this code:

pi
[1] 3.141593

Now try:

pi == 3.141593

What is the explanation for this output?

A word of warning about comparing numbers: you should never use == to compare two numbers unless they are integers (a data type which can specifically represent only whole numbers).

Computers may only represent decimal numbers with a certain degree of precision, so two numbers which look the same when printed out by R, may actually have different underlying representations and therefore be different by a small margin of error (called Machine numeric tolerance).

Instead you should use the all.equal function.

Further reading: http://floating-point-gui.de/

Variables and assignment

We can store values in variables using the assignment operator <-, like this:

x <- 1/40

Notice that assignment does not print a value. Instead, we stored it for later in something called a variable. x now contains the value 0.025:

x
[1] 0.025

More precisely, the stored value is a decimal approximation of this fraction called a floating point number.

Look for the Environment tab in one of the panes of RStudio, and you will see that x and its value have appeared. Our variable x can be used in place of a number in any calculation that expects a number:

log(x)
[1] -3.688879

Notice also that variables can be reassigned:

x <- 100

x used to contain the value 0.025 and and now it has the value 100.

Assignment values can contain the variable being assigned to:

x <- x + 1 #notice how RStudio updates its description of x on the top right tab
y <- x * 2

The right hand side of the assignment can be any valid R expression. The right hand side is fully evaluated before the assignment occurs.

Missing data

For all data types, it is possible to have missing values. In R, missing values are represented as NA. It is very important to understand this is different to 0, or "", which are each values in themselves. NA means missing (or not available).

If you want to check whether the variable x is NA it would be natural to use the equality operator (==):

x <- NA
x == NA
[1] NA

Using == with NA returns NA, because making a comparison to a missing value doesn’t make sense. Instead we need to check for the “state of missingness” rather than a value. We can do this with the is.na() function:

x <- NA
is.na(x)
[1] TRUE

Naming things

Object names can contain letters, numbers, underscores and periods. They cannot start with a number nor contain spaces at all. Different people use different conventions for long variable names, which include:

this_is_snake_case
otherPeopleUseCamelCase
some.people.use.periods
And_aFew.People_RENOUNCEconvention

Hadley Wickham recommends snake_case. What you use is up to you, but be consistent.

It is also possible to use the = operator for assignment:

x = 1/40

But this is much less common among R users. The most important thing is to be consistent with the operator you use. There are occasionally places where it is less confusing to use <- than =, and it is the most common symbol used in the community. So the recommendation is to use <-.

Challenge 1

Which of the following are valid R variable names?

min_height
max.height
_age
.mass
MaxLength
min-length
2widths
celsius2kelvin

Solution to challenge 1

The following can be used as R variables:

min_height
max.height
MaxLength
celsius2kelvin

The following creates a hidden variable:

.mass

The following will not be able to be used to create a variable

_age
min-length
2widths

Challenge 2

What will be the value of each variable after each statement in the following program?

mass <- 47.5
age <- 122
mass <- mass * 2.3
age <- age - 20

Solution to challenge 2

mass <- 47.5

This will give a value of 47.5 for the variable mass

age <- 122

This will give a value of 122 for the variable age

mass <- mass * 2.3

This will multiply the existing value of 47.5 by 2.3 to give a new value of 109.25 to the variable mass.

age <- age - 20

This will subtract 20 from the existing value of 122 to give a new value of 102 to the variable age.

Challenge 3

Run the code from the previous challenge, and write a command to compare mass to age. Is mass larger than age?

Solution to challenge 3

One way of answering this question in R is to use the > to set up the following:

mass > age
[1] TRUE

This should yield a boolean value of TRUE since 109.25 is greater than 102.

Commenting

Comments are ‘notes’ that are added to your script to provide further details for a human to read. They are ignored by R when the code is run. To add comments to your code, just type a # before your note text.

It’s a good habit to get into writing comments about what the code you’re writing is for - think of them as notes to help a future user (probably you!) understand why the code is there.

# this is a comment line
# a <- 5 this code will not assign 5 to the variable a
a <- 5 #but this line will

Functions

Functions are a stored list of instructions that can be “called” by a user. R has lots of built in functions to perform many different tasks.

To call a function, we type its name, followed by open and closing parentheses, like function_name().

Many functions take arguments, which are a list of parameters that can be given to the function to modify its behaviour. In R, argument values are defined with an = sign, in the form of: function_name(arg1 = val1, arg2 = val2).

Some functions have some arguments that must be defined, and others that are optional.

Tip: Remembering/finding function names and arguments

To use a function, for example seq(), which makes regular sequences of numbers, type se and hit TAB. RStudio will provide a popup which will show possible completions. Specify seq() by typing the next letter “q”, or by using Up/Down arrows to select.
Inside the parentheses, RStudio will show a list of the arguments that the function expects. To display the details in the Help tab in the lower right pane, press F1.

seq(1, 10)  # seq function
 [1]  1  2  3  4  5  6  7  8  9 10

Typing a ? before the name of a function will open its help page. As well as providing a detailed description of the function and how it works, scrolling to the bottom of the help page will usually show a collection of code examples which illustrate function usage.

Mathematical functions

R has many built in mathematical functions. To call a function, we simply type its name, followed by open and closing parentheses. Anything we type inside the parentheses is called the function’s arguments:

sin(1)  # trigonometry functions
[1] 0.841471
log10(10) # base-10 logarithm
[1] 1
exp(0.5) # e^(1/2)
[1] 1.648721

Vectorization

One final thing to be aware of is that R is vectorized, meaning that variables and functions can have vectors (which we’ll describe soon) as values. In contrast to physics and mathematics, a vector in R describes a set of values in a certain order of the same data type. For example

1:5
[1] 1 2 3 4 5
2^(1:5)
[1]  2  4  8 16 32
x <- 1:5
2^x
[1]  2  4  8 16 32

This is incredibly powerful and makes for efficient and readable code.

Managing your environment

There are a few useful commands you can use to interact with objects available in an R session.

ls will list all of the variables and functions stored in the global environment (your working R session):

ls()
 [1] "a"             "age"           "args"          "dest_md"      
 [5] "mass"          "missing_pkgs"  "required_pkgs" "src_rmd"      
 [9] "x"             "y"            

Tip: hidden objects

ls will hide any variables or functions starting with a “.” by default. To list all objects, type ls(all.names=TRUE) instead

Note here that we didn’t give any arguments to ls, but we still needed to give the parentheses to tell R to call the function.

If we type ls by itself, R will print out the source code for that function!

ls
function (name, pos = -1L, envir = as.environment(pos), all.names = FALSE, 
    pattern, sorted = TRUE) 
{
    if (!missing(name)) {
        pos <- tryCatch(name, error = function(e) e)
        if (inherits(pos, "error")) {
            name <- substitute(name)
            if (!is.character(name)) 
                name <- deparse(name)
            warning(gettextf("%s converted to character string", 
                sQuote(name)), domain = NA)
            pos <- name
        }
    }
    all.names <- .Internal(ls(envir, all.names, sorted))
    if (!missing(pattern)) {
        if ((ll <- length(grep("[", pattern, fixed = TRUE))) && 
            ll != length(grep("]", pattern, fixed = TRUE))) {
            if (pattern == "[") {
                pattern <- "\\["
                warning("replaced regular expression pattern '[' by  '\\\\['")
            }
            else if (length(grep("[^\\\\]\\[<-", pattern))) {
                pattern <- sub("\\[<-", "\\\\\\[<-", pattern)
                warning("replaced '[<-' by '\\\\[<-' in regular expression pattern")
            }
        }
        grep(pattern, all.names, value = TRUE)
    }
    else all.names
}
<bytecode: 0x5617134b21b8>
<environment: namespace:base>

You can use rm to delete objects you no longer need:

rm(x)

If you have lots of things in your environment and want to delete all of them, you can pass the results of ls to the rm function:

rm(list = ls())

In this case we’ve combined the two. Like the order of operations, anything inside the innermost parentheses is evaluated first, and so on.

In this case we’ve specified that the results of ls should be used for the list argument in rm. When assigning values to arguments by name, you must use the = operator!!

If instead we use <-, there will be unintended side effects, or you may get an error message:

rm(list <- ls())
Error in rm(list <- ls()): ... must contain names or character strings

Tip: Warnings vs. Errors

Pay attention when R does something unexpected! Errors, like above, are thrown when R cannot proceed with a calculation. Warnings on the other hand usually mean that the function has run, but it probably hasn’t worked as expected.

In both cases, the message that R prints out usually give you clues how to fix a problem.

Packages

In R, a package is a collection of functions and documentation that are bundled together to provide some functionality. They are a convenient and standardised way for the community to share code with each other. As of this writing, there are over 10,000 packages available on CRAN (the comprehensive R archive network). R and RStudio have functionality for managing packages:

Challenge 4

Clean up your working environment by deleting the mass and age variables.

Solution to challenge 4

We can use the rm command to accomplish this task

rm(age, mass)
Warning in rm(age, mass): object 'age' not found
Warning in rm(age, mass): object 'mass' not found

Before we go on, make sure you have the tidyverse package installed. You can check by running library(tidyverse), and if it’s not available, you can install it with install.packages(tidyverse).

Key Points

  • R has the usual arithmetic operators and mathematical functions.

  • Use <- to assign values to variables.

  • Use ls() to list the variables in a program.

  • Use rm() to delete objects in a program.

  • Use install.packages() to install packages.