This lesson is being piloted (Beta version)

R Language Basics

Overview

Teaching: 30 min
Exercises: 20 min
Questions
  • How to do simple calculations in R?

  • How to assign values to variables and call functions?

  • What are R’s vectors, vector data types, and vectorization?

  • How to install packages?

  • How can I get help in R?

  • What is an R Markdown file and how can I create one?

Objectives
  • To understand variables and how to assign to them

  • To be able to use mathematical and comparison operations

  • To be able to call functions

  • To be able to find and use packages

  • To be able to read R help files for functions and special operators.

  • To be able to seek help from your peers.

  • To be able to create and use R Markdown files

Introduction to R

R Operators

The simplest thing you could do with R is arithmetic:

1 + 100
[1] 101

Here we used to numbers and a + sign, which is called an operator. An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

Arithmetic operators

There are several arithmetic operators we can use and they should look familiar to you. If you use several of them (e.g., `5 + 2 *3), the order of operations is the same as you would have learned back in school. The list below is arranged from highest to lowest precedence:

Arithmetic operations

Operator Description
( ) Parentheses
^ or ** Exponents
/ Divide
* Multiply
- Subtract
+ Add

Examples

3 + 5 * 2^5
[1] 163

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)^5
[1] 1048576

Really small or large numbers get a scientific notation:

2/10000
[1] 2e-04

You can write numbers in scientific notation too:

5e3 
[1] 5000

Like bash, if you type in an incomplete command, R will wait for you to complete it. 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

If you’re using R from the commandline instead of from within RStudio, you need to use Ctrl+C instead of Esc to cancel the command. 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 its taking much longer than you expect), or to get rid of the code you’re currently writing.

Relational Operators

R also has relational operators that allow us to do comparison:

R Relational Operators

Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Examples

1 == 1; # equality (note two equals signs, read as "is equal to")  
[1] TRUE
1 != 1; # inequality (read as "is not equal to") 
[1] FALSE
1 <  2; # less than  
[1] TRUE
# etc

Comparing Numbers

Let’s compare 0.1 + 0.2 and 0.3. What do you think?

 0.1 + 0.2 == 0.3
 [1] FALSE

What’s happened?
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). So, unless you compare two integers, you should use the all.equal function:

 all.equal(0.1 + 0.2, 0.3)
 [1] TRUE

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

Other operators

There are several other types of operators:

We will see some of them in the next section and talk more about them in latter lessons (but see here if you can’t wait). Before we do it, we need to introduce variables.

Variables and assignment

A variable provides us with named storage that our programs can manipulate. We can store values in variables using the assignment operator <-:

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

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:

x^2
[1] 0.000625

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
x
[1] 101

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

Tip: A shortcut for assignment operator

IN RStudio, you can create the <- assignment operator in one keystroke using Option - (that’s a dash) on OS X or Alt - on Windows/Linux.

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

x = 1/40

But this is much less common among R users. So the recommendation is to use <-.

Naming variables

Variable 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, these include

  • periods.between.words
  • underscores_between_words
  • camelCaseToSeparateWords What you use is up to you, but be consistent.

Warning:

Notice, that R does not use a special symbol to distinguish between variable and simple text. Instead, the text is placed in double quotes “text”. If R complains that the object text does not exist, you probably forgot to use the quotes!

Reserved words

Reserved words in R programming are a set of words that have special meaning and cannot be used as an identifier (variable name, function name etc.). To view the list of reserved words you can type help(reserved) or ?reserved at the R command prompt.

Vectorization

One final thing to be aware of is that R is vectorized, meaning that variables and functions can have vectors as values. We can create vectors using several commands:

Vectorization

Command Description
c(2, 4, 6) Join elements into a vector
1:5 Create an integer sequence
seq(2, 3, by=0.5) Create a sequence with a specific increment
rep(1:2, times=3) Repeat a vector
rep(1:2, each=3) Repeat elements of a vector

Examples

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; we will discuss this further in an upcoming lesson.

Notice that in the table above we see some functions that can be recognized by parenthesis that follow one or more letters (e.g., seq(2, 3, by=0.5)). R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions. You can see some additional examples of in-build functions in this handy Cheat Sheet

Managing your environment

There are a few useful commands you can use to interact with the R session.

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

ls() # to list files use list.files() function
[1] "args"    "dest_md" "op"      "src_rmd" "x"      

Tip: hidden objects

Like in the shell, 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 given 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: 0x7f9b3d394c38>
<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.

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.

R Packages

It is possible to add functions to R by writing a package, or by obtaining a package written by someone else. There are over 7,000 packages available on CRAN (the comprehensive R archive network). R and RStudio have functionality for managing packages:

Writing your own code

Good coding style is like using correct punctuation. You can manage without it, but it sure makes things easier to read. As with styles of punctuation, there are many possible variations. Google’s R style guide is a good place to start. The formatR package, by Yihui Xie, makes it easier to clean up poorly formatted code. Make sure to read the notes on the wiki before using it.

Looking for help

Reading Help files

R, and every package, provide help files for functions. To search for help use:

?function_name
help(function_name)

This will load up a help page in RStudio (or as plain text in R by itself).

Note that each help page is broken down into several sections, including Description, Usage, Arguments, Examples, etc.

Operators

To seek help on operators, use quotes:

?"+"

Getting help on packages

Many packages come with “vignettes”: tutorials and extended example documentation. Without any arguments, vignette() will list all vignettes for all installed packages; vignette(package="package-name") will list all available vignettes for package-name, and vignette("vignette-name") will open the specified vignette.

If a package doesn’t have any vignettes, you can usually find help by typing help("package-name").

When you kind of remember the function

If you’re not sure what package a function is in, or how it’s specifically spelled you can do a fuzzy search:

??function_name

When you have no idea where to begin

If you don’t know what function or package you need to use CRAN Task Views is a specially maintained list of packages grouped into fields. This can be a good starting point.

When your code doesn’t work: seeking help from your peers

If you’re having trouble using a function, 9 times out of 10, the answers you are seeking have already been answered on Stack Overflow. You can search using the [r] tag.

If you can’t find the answer, there are two useful functions to help you ask a question from your peers:

?dput

Will dump the data you’re working with into a format so that it can be copy and pasted by anyone else into their R session.

sessionInfo()
R version 4.0.4 (2021-02-15)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.7

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] knitr_1.31

loaded via a namespace (and not attached):
[1] compiler_4.0.4 magrittr_2.0.1 tools_4.0.4    stringi_1.5.3  stringr_1.4.0 
[6] xfun_0.22      evaluate_0.14 

Will print out your current version of R, as well as any packages you have loaded.

Vocabulary

As with any language, it’s important to work on your R vocabulary. Here is a good place to start

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

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

Solution to challenge 3

We can use the rm command to accomplish this task

rm(age, mass)

Challenge 4

Install packages in the tidyverse collection

Solution to challenge 4

We can use the install.packages() command to install the required packages.

install.packages("tidyverse")

Challenge 5

Use help to find a function (and its associated parameters) that you could use to load data from a csv file in which columns are delimited with “\t” (tab) and the decimal point is a “.” (period). This check for decimal separator is important, especially if you are working with international colleagues, because different countries have different conventions for the decimal point (i.e. comma vs period). hint: use ??csv to lookup csv related functions.

```

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

  • Use library(packagename)to make a package available for use

  • Use help() to get online help in R.