Introduction to R and RStudio (reference card)

Variables

Store values using the assignment operator <- (or =):

weight <- 26

To display the value use the name of the variable:

weight <- 26
weight
[1] 26

Comments

Write information intended for people, not the computer using #:

# This whole line is a comment
weight <- 26 # The end of this line is a comment

Functions

Run functions using name_of_function(arguments):

round(weight, 0)
[1] 26

Vectors

Store multiple values together in a vector using c():

count <- c(9, 16, 3, 10)
count
[1]  9 16  3 10

Many functions take a vector as an argument and return a single value:

mean(count)
[1] 9.5

Slicing vectors

Get a piece of a vector:

count[2:3]
[1] 16  3

Null values

Nulls are stored as NA:

count_na <- c(9, 16, NA, 10)
count_na
[1]  9 16 NA 10

Ignore NA in calculations on vectors with na.rm = TRUE:

mean(count_na, na.rm = TRUE)
[1] 11.66667

Vector math

Doing math with vectors will do the calculation elementwise and return a vector of the same length as the original vectors.

count <- c(9, 16, 3, 10)
area <- c(3, 5, 1.9, 2.7)
density <- count / area
density
[1] 3.000000 3.200000 1.578947 3.703704

Filtering vectors (subsetting)

Select parts of a vector based on conditions using [].
To check if two things are equal use == (not =).
Other operators include <, <=, >, >=.

states <- c("FL", "FL", "GA", "SC")
count <- c(9, 16, 3, 10)
area <- c(3, 5, 1.9, 2.7)

area[states == 'FL']
[1] 3 5
count[area > 2]
[1]  9 16 10
count[count > 2]
[1]  9 16  3 10