Loading a Library

Almost every script you write will need to load a library. Do this at the top of the script. In the code chunk below, load the tidyverse and readxl libraries. You can check if you have a library under the Packages tab in the lower right RStudio pane. You might need to use install.packages("tidyverse") to install these libraries on your computer, but never put install.packages() in a script (just type that command directly into the console window).

library(tidyverse)
library(readxl)

Assigning Variables and Data Types

The main data types you will use are numeric (integer or double), character, and boolean.

You assign data to variables with the assignment operator <-. Assign the following variables:

four <- 4L
one_plus_3 <- 1L + 3L
double_four <- 4
lower <- "lisa"
UPPER <- "LISA"

Comparison

The comparison operators, such as ==, >, <, >=, and <= let you compare data and/or variables. Remember, = sets the left side of the equation equal to the right side, while == checks if the left and right sides are equivalent.

If you assign a variable to the outcome of a comparison, such as is_equal <- 10 == 5 + 5, the variable will be TRUE if the comparison is true and FALSE if the comparison is false. Assign the following variables to the outcome of the specified comparison:

comp_1_eq_2 <- 1L == 2L
comp_a_eq_A <- "a" == "A"
comp_10_lt_20 <- 10 < 20
comp_four_gte_one_plus_3 <- four >= one_plus_3

Forming a vector

A vector is a list of 1 or more items of the same data type. Create the following variables:

beatles <- c("John", "Paul", "George", "Ringo")
one_to_ten <- 1:10
evens <- c(2, 4, 6, 8, 10) # seq(2, 10, by = 2)
a_to_e <- letters[1:5]

Vectorised Operations

by_tens <- one_to_ten * 10
squares <- 1:10 * 1:10 # (1:10)^2
a_to_e_1 <- paste0(a_to_e, 1:5)

Loading Data

You can load data straight from a website using the URL. Use tidyverse functions for reading CSV and Excel files to create the following variables:

infmort <- read_csv("https://psyteachr.github.io/msc-data-skills/data/infmort.csv")
## Parsed with column specification:
## cols(
##   Country = col_character(),
##   Year = col_double(),
##   `Infant mortality rate (probability of dying between birth and age 1 per 1000 live births)` = col_character()
## )
matmort <- read_xls("data/matmort.xls")