R 101

The basics

Interacting with R

What will happen when you enter these commands? Try it out.

Saving data in variables

[1] 10
[1] 21
[1] 0.4761905

If you’re working with very large numbers you can use scientific notation:

[1] 2e+10
[1] 2e+10
[1] TRUE

In that last line we used the comparison operator ==; it tests whether or not two values are equivalent.

Everything is a vector

You can see how many elements a vector holds using the length function:

[1] 1
[1] 1
[1] 10

Composing vectors

[1] 1 2 3 4
[1] 15 16 17 18
[1] 10 12 14 16

Value recycling

[1]  6  8  8 10
Warning in d + c(1, 2, 3): longer object length is not a multiple of
shorter object length
[1]  6  8 10  9

So, for example, we could flip the sign of every other number in a vector with:

[1]  5 -6  7 -8

Types of variables

Strings

[1] "a"
[1] TRUE
[1] "a" "b" "c" "d"
a   b   c
a
b
c

Boolean values

Boolean can either be “True” or “False”, and represent a variable with binary values. To create Boolean use TRUE or FALSE:

[1] TRUE
[1] FALSE
[1]  TRUE  TRUE FALSE
[1] FALSE

Missing Data

[1]  1  2 NA  4
[1] "a" NA  "c" NA 
[1]  TRUE FALSE    NA FALSE
[1] FALSE  TRUE

A note about NULL

NULL is used to signify unassigned variables:

NULL
[1] TRUE

Indexing syntax in R

Extracting values

Let’s say we have a vector of numbers:

We can extract elements from 1D vectors using the index syntax [] and integers:

[1] 10 20 30 40 50
[1] 10
[1] 30

We can use integer vectors with more than one element inside of our index [...]’s::

[1] 10 30

You can use the : operator to easily create a sequence of numbers:

[1] 2 3 4
[1] 20 30 40

[1] 10 20 30 40 50
[1] 20 30 40 50
[1] 10

Logical operators always return a logical vector:

[1] FALSE FALSE  TRUE  TRUE  TRUE
[1]  TRUE  TRUE FALSE FALSE FALSE
[1] FALSE FALSE  TRUE FALSE FALSE
[1]  TRUE  TRUE FALSE  TRUE  TRUE

The %in% operator asks if the first set of numbers can be found in the second:

[1] TRUE
[1]  TRUE FALSE

The ! operator negates (flips) each value of a logical vector:

[1] FALSE
[1]  TRUE  TRUE FALSE FALSE FALSE

So how can we combine logical comparisons with indexing?

[1] 30 40 50
[1] 10 20

You can get fancy…

[1] 10 20 30 40 50

What happened there? If you need help figuring it out, look up the %% (modulo) operator on the help panel.

Assigning values

[1] 10 20 30 40 50
[1]  10  20 100  40  50
[1] 10  1  2 40 50

Failure is an option!

It doesn’t work and it’s R’s fault!

So how can you shift your thinking to get moving again when you’re stuck and frustrated?

Play, play and play some more!

  • Footnote: about the most destructive thing you can do is erase all of your files. Please don’t do that.

Try to invalidate your assumptions

Read the manual