W#03 Data Import, Data Wrangling, Relational Data, Exploratory Data Analysis

With material adopted from Data Science in a Box and R4DS

Jan Lorenz

Data Import - short version

readr and readxl

  • read_csv() - comma delimited files
  • read_csv2() - semicolon delimited files (common where “,” is used as decimal place)
  • read_tsv() - tab delimited files
  • read_delim() - reads in files with any delimiter

  • read_excel() read xls or xlsx files from MS Excel

Other data formats

R packages, analog libraries will exist for python

  • googlesheets4: Google Sheets
  • haven: SPSS, Stata, and SAS files
  • DBI, along with a database specific backend (e.g. RMySQL, RSQLite, RPostgreSQL etc): allows you to run SQL queries against a database and return a data frame
  • jsonlite: JSON
  • xml2: xml
  • rvest: web scraping
  • httr: web APIs

Comma-separated values (CSV)

We use CSV file when there is no certain reason to do otherwise.1

CSV files are delimited text file

  • Can be viewed with any text editor
  • Show each row of the data frame in a line
  • Separates the content of columns by commas (or the delimiter character)
  • Each cell could be surrounded by quotes (when long text with commas (!) is in cells)
  • The first line is interpreted as listing the variable names by default

readr tries to guess the data type of variables

You can also customize it yourself!

Data import workflow

  1. You download your CSV file to the data/ directory. You may use download.file() for this, but make sure you do not download large amounts of data each time you render your file!
  2. Read the data with data <- read_csv("data/FILENAME.csv") and read the report in the console.
  3. Explore if you are happy and iterate by customizing the data import line using specifications until the data is as you want it to be.

Good practices to document the data download:

  • One or low number of files: Put the download line(s) in you main document, but comment out # after usage.
  • Write a script (data-download.r) to document the download commands.
  • Make your code check first if the file already exist, like this if (!(file.exists("DATA_FILE.csv"))) {DOWNLOAD-CODE}

1. Download, 2. Read

This downloads data only if the file does not exist. Then it loads it.

if (!file.exists("data/hotels.csv")) {
  download.file(url = "https://raw.githubusercontent.com/rstudio-education/datascience-box/main/course-materials/_slides/u2-d06-grammar-wrangle/data/hotels.csv", 
                destfile = "data/hotels.csv")
}
hotels <- read_csv("data/hotels.csv")
Rows: 119390 Columns: 32
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (13): hotel, arrival_date_month, meal, country, market_segment, distrib...
dbl  (18): is_canceled, lead_time, arrival_date_year, arrival_date_week_numb...
date  (1): reservation_status_date

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Output is a summary how read_csv guessed the data types of columns.

3. Explore using spec()

All details to check or customize:

spec(hotels)
cols(
  hotel = col_character(),
  is_canceled = col_double(),
  lead_time = col_double(),
  arrival_date_year = col_double(),
  arrival_date_month = col_character(),
  arrival_date_week_number = col_double(),
  arrival_date_day_of_month = col_double(),
  stays_in_weekend_nights = col_double(),
  stays_in_week_nights = col_double(),
  adults = col_double(),
  children = col_double(),
  babies = col_double(),
  meal = col_character(),
  country = col_character(),
  market_segment = col_character(),
  distribution_channel = col_character(),
  is_repeated_guest = col_double(),
  previous_cancellations = col_double(),
  previous_bookings_not_canceled = col_double(),
  reserved_room_type = col_character(),
  assigned_room_type = col_character(),
  booking_changes = col_double(),
  deposit_type = col_character(),
  agent = col_character(),
  company = col_character(),
  days_in_waiting_list = col_double(),
  customer_type = col_character(),
  adr = col_double(),
  required_car_parking_spaces = col_double(),
  total_of_special_requests = col_double(),
  reservation_status = col_character(),
  reservation_status_date = col_date(format = "")
)

Finalize data import, option 1

When

  • all columns are how they should
  • you consider it not necessary to document the specifications

Then use show_col_types = FALSE to quiet the reading message.

hotels <- read_csv("data/hotels.csv", show_col_types = FALSE)

Finalize data import, option 2

  • Copy the spec(hotels) output into the col_types argument
  • If necessary, customize it
hotels <- read_csv("data/hotels.csv", col_types = cols(
  hotel = col_character(),
  is_canceled = col_logical(),
  lead_time = col_integer(),
  arrival_date_year = col_integer(),
  arrival_date_month = col_character(),
  arrival_date_week_number = col_integer(),
  arrival_date_day_of_month = col_integer(),
  stays_in_weekend_nights = col_integer(),
  stays_in_week_nights = col_integer(),
  adults = col_integer(),
  children = col_integer(),
  babies = col_integer(),
  meal = col_character(),
  country = col_character(),
  market_segment = col_character(),
  distribution_channel = col_character(),
  is_repeated_guest = col_logical(),
  previous_cancellations = col_integer(),
  previous_bookings_not_canceled = col_integer(),
  reserved_room_type = col_character(),
  assigned_room_type = col_character(),
  booking_changes = col_integer(),
  deposit_type = col_character(),
  agent = col_integer(),
  company = col_integer(),
  days_in_waiting_list = col_integer(),
  customer_type = col_character(),
  adr = col_double(),
  required_car_parking_spaces = col_integer(),
  total_of_special_requests = col_integer(),
  reservation_status = col_character(),
  reservation_status_date = col_date(format = "")
))

Columns types

type function data type
col_character() character
col_date() date
col_datetime() POSIXct (date-time)
col_double() double (numeric)
col_factor() factor
col_guess() let readr guess (default)
col_integer() integer
col_logical() logical
col_number() numbers mixed with non-number characters
col_skip() do not read
col_time() time

Hotels data

  • Data from two hotels: one resort and one city hotel
  • Observations: Each row represents a hotel booking

First look on data

Type the name of the data frame

hotels
# A tibble: 119,390 × 32
   hotel        is_canceled lead_time arrival_date_year arrival_date_month
   <chr>        <lgl>           <int>             <int> <chr>             
 1 Resort Hotel FALSE             342              2015 July              
 2 Resort Hotel FALSE             737              2015 July              
 3 Resort Hotel FALSE               7              2015 July              
 4 Resort Hotel FALSE              13              2015 July              
 5 Resort Hotel FALSE              14              2015 July              
 6 Resort Hotel FALSE              14              2015 July              
 7 Resort Hotel FALSE               0              2015 July              
 8 Resort Hotel FALSE               9              2015 July              
 9 Resort Hotel TRUE               85              2015 July              
10 Resort Hotel TRUE               75              2015 July              
# ℹ 119,380 more rows
# ℹ 27 more variables: arrival_date_week_number <int>,
#   arrival_date_day_of_month <int>, stays_in_weekend_nights <int>,
#   stays_in_week_nights <int>, adults <int>, children <int>, babies <int>,
#   meal <chr>, country <chr>, market_segment <chr>,
#   distribution_channel <chr>, is_repeated_guest <lgl>,
#   previous_cancellations <int>, previous_bookings_not_canceled <int>, …

Look on variable names

names(hotels)
 [1] "hotel"                          "is_canceled"                   
 [3] "lead_time"                      "arrival_date_year"             
 [5] "arrival_date_month"             "arrival_date_week_number"      
 [7] "arrival_date_day_of_month"      "stays_in_weekend_nights"       
 [9] "stays_in_week_nights"           "adults"                        
[11] "children"                       "babies"                        
[13] "meal"                           "country"                       
[15] "market_segment"                 "distribution_channel"          
[17] "is_repeated_guest"              "previous_cancellations"        
[19] "previous_bookings_not_canceled" "reserved_room_type"            
[21] "assigned_room_type"             "booking_changes"               
[23] "deposit_type"                   "agent"                         
[25] "company"                        "days_in_waiting_list"          
[27] "customer_type"                  "adr"                           
[29] "required_car_parking_spaces"    "total_of_special_requests"     
[31] "reservation_status"             "reservation_status_date"       

Second look with glimpse

glimpse(hotels)
Rows: 119,390
Columns: 32
$ hotel                          <chr> "Resort Hotel", "Resort Hotel", "Resort…
$ is_canceled                    <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALS…
$ lead_time                      <int> 342, 737, 7, 13, 14, 14, 0, 9, 85, 75, …
$ arrival_date_year              <int> 2015, 2015, 2015, 2015, 2015, 2015, 201…
$ arrival_date_month             <chr> "July", "July", "July", "July", "July",…
$ arrival_date_week_number       <int> 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,…
$ arrival_date_day_of_month      <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, …
$ stays_in_weekend_nights        <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ stays_in_week_nights           <int> 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, …
$ adults                         <int> 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, …
$ children                       <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ babies                         <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ meal                           <chr> "BB", "BB", "BB", "BB", "BB", "BB", "BB…
$ country                        <chr> "PRT", "PRT", "GBR", "GBR", "GBR", "GBR…
$ market_segment                 <chr> "Direct", "Direct", "Direct", "Corporat…
$ distribution_channel           <chr> "Direct", "Direct", "Direct", "Corporat…
$ is_repeated_guest              <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALS…
$ previous_cancellations         <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ previous_bookings_not_canceled <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ reserved_room_type             <chr> "C", "C", "A", "A", "A", "A", "C", "C",…
$ assigned_room_type             <chr> "C", "C", "C", "A", "A", "A", "C", "C",…
$ booking_changes                <int> 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ deposit_type                   <chr> "No Deposit", "No Deposit", "No Deposit…
$ agent                          <int> NA, NA, NA, 304, 240, 240, NA, 303, 240…
$ company                        <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,…
$ days_in_waiting_list           <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ customer_type                  <chr> "Transient", "Transient", "Transient", …
$ adr                            <dbl> 0.00, 0.00, 75.00, 75.00, 98.00, 98.00,…
$ required_car_parking_spaces    <int> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
$ total_of_special_requests      <int> 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 3, …
$ reservation_status             <chr> "Check-Out", "Check-Out", "Check-Out", …
$ reservation_status_date        <date> 2015-07-01, 2015-07-01, 2015-07-02, 20…

Now, comes the data wrangling, transformation, …

Data Wrangling

Grammar of Data Wrangling

Grammar of data wrangling: Start with a dataset and pipe it through several manipulations with |>

mpg |> 
  filter(cyl == 8) |> 
  select(manufacturer, hwy) |> 
  group_by(manufacturer) |> 
  summarize(mean_hwy = mean(hwy))

Similar in python: Make a chain using . to apply pandas methods for data frames one after the other.

Similar in ggplot2: Creating a ggplot object, then add graphical layers (geom_ functions) with + (instead of a pipe)

ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = trans)) + 
  geom_point() + 
  geom_smooth()

What is the pipe |>?

x |> f(a,b) is the same as f(x,a,b)

The outcome of a command is put into the first argument of the next function call. Practice it it see that it is exactly identical!

Reasons for using pipes:

  • structure the sequence of your data operations from left to right
  • avoid nested function calls:
    nested: filter(select(hotels, hotel, adults), adults == 2)
    piped: hotels |> select(hotel, adults) |> filter(adults == 2)
    (base R: hotels[hotels$adults == 2, c("hotel", "adults")])
  • You’ll minimize the need for local variables and function definitions
  • You’ll make it easy to add steps anywhere in the sequence of operations

dplyr uses verbs to manipulate

  • select: pick columns by name
  • arrange: reorder rows
  • slice: pick rows using index(es)
  • filter: pick rows matching criteria
  • distinct: filter for unique rows
  • mutate: add new variables
  • summarise: reduce variables to values
  • group_by: for grouped operations
  • … (many more)

Data subsetting

select a single column

hotels |> select(lead_time)     
# A tibble: 119,390 × 1
   lead_time
       <int>
 1       342
 2       737
 3         7
 4        13
 5        14
 6        14
 7         0
 8         9
 9        85
10        75
# ℹ 119,380 more rows

Note: select(hotels, lead_time) is identical.

Why does piping |> work?

Every dplyr function

  • takes a data frame (tibble) as first argument
  • outputs a (manipulated) data frame (tibble)

Select more columns

hotels |> select(hotel, lead_time)     
# A tibble: 119,390 × 2
   hotel        lead_time
   <chr>            <int>
 1 Resort Hotel       342
 2 Resort Hotel       737
 3 Resort Hotel         7
 4 Resort Hotel        13
 5 Resort Hotel        14
 6 Resort Hotel        14
 7 Resort Hotel         0
 8 Resort Hotel         9
 9 Resort Hotel        85
10 Resort Hotel        75
# ℹ 119,380 more rows

Note that hotel is a variable, but hotels the data frame object name

Select helper starts_with

hotels |> select(starts_with("arrival"))
# A tibble: 119,390 × 4
   arrival_date_year arrival_date_month arrival_date_week_number
               <int> <chr>                                 <int>
 1              2015 July                                     27
 2              2015 July                                     27
 3              2015 July                                     27
 4              2015 July                                     27
 5              2015 July                                     27
 6              2015 July                                     27
 7              2015 July                                     27
 8              2015 July                                     27
 9              2015 July                                     27
10              2015 July                                     27
# ℹ 119,380 more rows
# ℹ 1 more variable: arrival_date_day_of_month <int>

Bring columns to the front

hotels |> select(hotel, market_segment, children, everything())
# A tibble: 119,390 × 32
   hotel        market_segment children is_canceled lead_time arrival_date_year
   <chr>        <chr>             <int> <lgl>           <int>             <int>
 1 Resort Hotel Direct                0 FALSE             342              2015
 2 Resort Hotel Direct                0 FALSE             737              2015
 3 Resort Hotel Direct                0 FALSE               7              2015
 4 Resort Hotel Corporate             0 FALSE              13              2015
 5 Resort Hotel Online TA             0 FALSE              14              2015
 6 Resort Hotel Online TA             0 FALSE              14              2015
 7 Resort Hotel Direct                0 FALSE               0              2015
 8 Resort Hotel Direct                0 FALSE               9              2015
 9 Resort Hotel Online TA             0 TRUE               85              2015
10 Resort Hotel Offline TA/TO         0 TRUE               75              2015
# ℹ 119,380 more rows
# ℹ 26 more variables: arrival_date_month <chr>,
#   arrival_date_week_number <int>, arrival_date_day_of_month <int>,
#   stays_in_weekend_nights <int>, stays_in_week_nights <int>, adults <int>,
#   babies <int>, meal <chr>, country <chr>, distribution_channel <chr>,
#   is_repeated_guest <lgl>, previous_cancellations <int>,
#   previous_bookings_not_canceled <int>, reserved_room_type <chr>, …

More select helpers

  • starts_with(): Starts with a prefix
  • ends_with(): Ends with a suffix
  • contains(): Contains a literal string
  • num_range(): Matches a numerical range like x01, x02, x03
  • one_of(): Matches variable names in a character vector
  • everything(): Matches all variables
  • last_col(): Select last variable, possibly with an offset
  • matches(): Matches a regular expression (a sequence of symbols/characters expressing a string/pattern to be searched for within text)

slice for certain rows

hotels |> slice(2:4)
# A tibble: 3 × 32
  hotel        is_canceled lead_time arrival_date_year arrival_date_month
  <chr>        <lgl>           <int>             <int> <chr>             
1 Resort Hotel FALSE             737              2015 July              
2 Resort Hotel FALSE               7              2015 July              
3 Resort Hotel FALSE              13              2015 July              
# ℹ 27 more variables: arrival_date_week_number <int>,
#   arrival_date_day_of_month <int>, stays_in_weekend_nights <int>,
#   stays_in_week_nights <int>, adults <int>, children <int>, babies <int>,
#   meal <chr>, country <chr>, market_segment <chr>,
#   distribution_channel <chr>, is_repeated_guest <lgl>,
#   previous_cancellations <int>, previous_bookings_not_canceled <int>,
#   reserved_room_type <chr>, assigned_room_type <chr>, …

filter for rows with certain criteria

hotels |> filter(hotel == "City Hotel")
# A tibble: 79,330 × 32
   hotel      is_canceled lead_time arrival_date_year arrival_date_month
   <chr>      <lgl>           <int>             <int> <chr>             
 1 City Hotel FALSE               6              2015 July              
 2 City Hotel TRUE               88              2015 July              
 3 City Hotel TRUE               65              2015 July              
 4 City Hotel TRUE               92              2015 July              
 5 City Hotel TRUE              100              2015 July              
 6 City Hotel TRUE               79              2015 July              
 7 City Hotel FALSE               3              2015 July              
 8 City Hotel TRUE               63              2015 July              
 9 City Hotel TRUE               62              2015 July              
10 City Hotel TRUE               62              2015 July              
# ℹ 79,320 more rows
# ℹ 27 more variables: arrival_date_week_number <int>,
#   arrival_date_day_of_month <int>, stays_in_weekend_nights <int>,
#   stays_in_week_nights <int>, adults <int>, children <int>, babies <int>,
#   meal <chr>, country <chr>, market_segment <chr>,
#   distribution_channel <chr>, is_repeated_guest <lgl>,
#   previous_cancellations <int>, previous_bookings_not_canceled <int>, …

filter for multiple criteria

hotels |> filter(
  babies >= 1,
  children >= 1, 
  ) |> 
  select(hotel, adults, babies, children)
# A tibble: 175 × 4
   hotel        adults babies children
   <chr>         <int>  <int>    <int>
 1 Resort Hotel      2      1        1
 2 Resort Hotel      2      1        1
 3 Resort Hotel      2      1        1
 4 Resort Hotel      2      1        1
 5 Resort Hotel      2      1        1
 6 Resort Hotel      2      1        1
 7 Resort Hotel      2      1        1
 8 Resort Hotel      2      1        2
 9 Resort Hotel      2      1        2
10 Resort Hotel      1      1        2
# ℹ 165 more rows

Comma-separated conditions are interpreted as all these should be fulfilled.
This is identical to the logical AND &.
hotels |> filter(babies >= 1 & children >= 1)

filter for complexer criteria

hotels |> filter(
  babies >= 1 | children >= 1
  ) |> 
  select(hotel, adults, babies, children)
# A tibble: 9,332 × 4
   hotel        adults babies children
   <chr>         <int>  <int>    <int>
 1 Resort Hotel      2      0        1
 2 Resort Hotel      2      0        2
 3 Resort Hotel      2      0        2
 4 Resort Hotel      2      0        2
 5 Resort Hotel      2      0        1
 6 Resort Hotel      2      0        1
 7 Resort Hotel      1      0        2
 8 Resort Hotel      2      0        2
 9 Resort Hotel      2      1        0
10 Resort Hotel      2      1        0
# ℹ 9,322 more rows

| is the logical OR. Only one criterion needs to be fulfilled.

Logical operators1

operator definition
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
x & y x AND y
x | y x OR y
is.na(x) test if x is NA (missing data)
!is.na(x) test if x is not NA (not missing data)
x %in% y test if x is in y (often used for strings)
!(x %in% y) test if x is not in y
!x not x

Excursions: The Concept of Indexing

Select and filter can also be achieved by indexing.

In (base) R as well as in python.

Select ranges of rows and columns

hotels[1:3,5:7]
# A tibble: 3 × 3
  arrival_date_month arrival_date_week_number arrival_date_day_of_month
  <chr>                                 <int>                     <int>
1 July                                     27                         1
2 July                                     27                         1
3 July                                     27                         1

You can use any vector (with non-overshooting indexes)

hotels[c(1:3,100232),c(5:7,1)]
# A tibble: 4 × 4
  arrival_date_month arrival_date_week_number arrival_date_day_of_month hotel   
  <chr>                                 <int>                     <int> <chr>   
1 July                                     27                         1 Resort …
2 July                                     27                         1 Resort …
3 July                                     27                         1 Resort …
4 October                                  44                        23 City Ho…

python is 0-indexed, R is 1-indexed!

python: indexes go from 0 to n-1

R: indexes go from 1 to n

Be aware!

Note: There is no correct way. For some use cases one is more natural for others the other.

Analogy: In mathematics there is an unsettled debate if \(0 \in \mathbb{N}\) or \(0 \notin \mathbb{N}\)

Excursion: The Concept of Logical Indexing

With logical vectors you can select rows and columns

data <- tibble(x = LETTERS[1:5], y = letters[6:10])
data
# A tibble: 5 × 2
  x     y    
  <chr> <chr>
1 A     f    
2 B     g    
3 C     h    
4 D     i    
5 E     j    
data[c(TRUE,FALSE,TRUE,FALSE,TRUE),c(TRUE,FALSE)]
# A tibble: 3 × 1
  x    
  <chr>
1 A    
2 C    
3 E    

Logical vectors from conditional statements

data$x
[1] "A" "B" "C" "D" "E"
data$x %in% c("C","E")
[1] FALSE FALSE  TRUE FALSE  TRUE
data[data$x %in% c("C","E"),]
# A tibble: 2 × 2
  x     y    
  <chr> <chr>
1 C     h    
2 E     j    
data[data$x %in% c("C","E") | 
       data$y %in% c("h","i"),]
# A tibble: 3 × 2
  x     y    
  <chr> <chr>
1 C     h    
2 D     i    
3 E     j    
data |> 
  filter(
    x %in% c("C","E") | y %in% c("h","i")
    )
# A tibble: 3 × 2
  x     y    
  <chr> <chr>
1 C     h    
2 D     i    
3 E     j    

Unique combinations, arranging

distinct and arrange

hotels |> 
  distinct(hotel, market_segment) |> 
  arrange(hotel, market_segment)
# A tibble: 14 × 2
   hotel        market_segment
   <chr>        <chr>         
 1 City Hotel   Aviation      
 2 City Hotel   Complementary 
 3 City Hotel   Corporate     
 4 City Hotel   Direct        
 5 City Hotel   Groups        
 6 City Hotel   Offline TA/TO 
 7 City Hotel   Online TA     
 8 City Hotel   Undefined     
 9 Resort Hotel Complementary 
10 Resort Hotel Corporate     
11 Resort Hotel Direct        
12 Resort Hotel Groups        
13 Resort Hotel Offline TA/TO 
14 Resort Hotel Online TA     

Counting

count

hotels |> 
  count(hotel, market_segment) |>      # This produces a new variable n
  arrange(n)
# A tibble: 14 × 3
   hotel        market_segment     n
   <chr>        <chr>          <int>
 1 City Hotel   Undefined          2
 2 Resort Hotel Complementary    201
 3 City Hotel   Aviation         237
 4 City Hotel   Complementary    542
 5 Resort Hotel Corporate       2309
 6 City Hotel   Corporate       2986
 7 Resort Hotel Groups          5836
 8 City Hotel   Direct          6093
 9 Resort Hotel Direct          6513
10 Resort Hotel Offline TA/TO   7472
11 City Hotel   Groups         13975
12 City Hotel   Offline TA/TO  16747
13 Resort Hotel Online TA      17729
14 City Hotel   Online TA      38748

Data Transformation

Create a new variable with mutate

hotels |>
  mutate(little_ones = children + babies) |>
  select(children, babies, little_ones) |>
  arrange(desc(little_ones)) # This sorts in descending order. See the big things!
# A tibble: 119,390 × 3
   children babies little_ones
      <int>  <int>       <int>
 1       10      0          10
 2        0     10          10
 3        0      9           9
 4        2      1           3
 5        2      1           3
 6        2      1           3
 7        3      0           3
 8        2      1           3
 9        2      1           3
10        3      0           3
# ℹ 119,380 more rows

More mutating

hotels |>
  mutate(little_ones = children + babies) |>
  count(hotel, little_ones) |>
  mutate(prop = n / sum(n))
# A tibble: 12 × 4
   hotel        little_ones     n       prop
   <chr>              <int> <int>      <dbl>
 1 City Hotel             0 73923 0.619     
 2 City Hotel             1  3263 0.0273    
 3 City Hotel             2  2056 0.0172    
 4 City Hotel             3    82 0.000687  
 5 City Hotel             9     1 0.00000838
 6 City Hotel            10     1 0.00000838
 7 City Hotel            NA     4 0.0000335 
 8 Resort Hotel           0 36131 0.303     
 9 Resort Hotel           1  2183 0.0183    
10 Resort Hotel           2  1716 0.0144    
11 Resort Hotel           3    29 0.000243  
12 Resort Hotel          10     1 0.00000838

Summarizing

hotels |>
  summarize(mean_adr = mean(adr))
# A tibble: 1 × 1
  mean_adr
     <dbl>
1     102.
  • That shrinks the data frame to one row!
  • Don’t forget to name the new variable (here mean_adr)
  • You can use any function you can apply to a vector!
    (Sometimes you may need to write your own one.)

Grouped operations

hotels |>
  group_by(hotel) |>
  summarise(mean_adr = mean(adr))
# A tibble: 2 × 2
  hotel        mean_adr
  <chr>           <dbl>
1 City Hotel      105. 
2 Resort Hotel     95.0

Look at the grouping attributes:

hotels |>
  group_by(hotel)
# A tibble: 119,390 × 32
# Groups:   hotel [2]
   hotel        is_canceled lead_time arrival_date_year arrival_date_month
   <chr>        <lgl>           <int>             <int> <chr>             
 1 Resort Hotel FALSE             342              2015 July              
 2 Resort Hotel FALSE             737              2015 July              
 3 Resort Hotel FALSE               7              2015 July              
 4 Resort Hotel FALSE              13              2015 July              
 5 Resort Hotel FALSE              14              2015 July              
 6 Resort Hotel FALSE              14              2015 July              
 7 Resort Hotel FALSE               0              2015 July              
 8 Resort Hotel FALSE               9              2015 July              
 9 Resort Hotel TRUE               85              2015 July              
10 Resort Hotel TRUE               75              2015 July              
# ℹ 119,380 more rows
# ℹ 27 more variables: arrival_date_week_number <int>,
#   arrival_date_day_of_month <int>, stays_in_weekend_nights <int>,
#   stays_in_week_nights <int>, adults <int>, children <int>, babies <int>,
#   meal <chr>, country <chr>, market_segment <chr>,
#   distribution_channel <chr>, is_repeated_guest <lgl>,
#   previous_cancellations <int>, previous_bookings_not_canceled <int>, …

Grouping, summarizing, visualizing

hotels |>
  group_by(hotel, arrival_date_week_number) |>
  summarise(mean_adr = mean(adr)) |> 
  ggplot(aes(x = arrival_date_week_number, y = mean_adr, color = hotel)) +
  geom_line()

Where to find help

Resources

  • For systemic understanding: Learning resources linked in the syllabus
    • R for Data Science
    • Python Data Science Handbook
  • For quick overview to get inspiration
    • Cheatsheets (find some in RStudio -> Help, others by google)
      • ggplot2 Cheatsheet
      • dplyr Cheatsheet
  • For detailed help with a function
    • Help file of the function ?FUNCTION-NAME, or search box in Help tab
    • Reference page on the package webpage
  • Talk to ChatGPT? Does it work?

More under the hood

Named vectors

All types of vectors can be named upon creation

c(Num1 = 4, Second = 7, Last = 8)
  Num1 Second   Last 
     4      7      8 

or names can be set afterward.

x <- 1:4
y <- set_names(x, c("a","b","c","d"))
y
a b c d 
1 2 3 4 

Named vectors can be used for subsetting.

y[c("b","d")]
b d 
2 4 

Reminder: Indexing and vectorized thinking

x <- set_names(1:10,LETTERS[1:10])
x
 A  B  C  D  E  F  G  H  I  J 
 1  2  3  4  5  6  7  8  9 10 
x[c(4,2,1,1,1,1,4,1,5)]
D B A A A A D A E 
4 2 1 1 1 1 4 1 5 

Removing with negative index numbers.

x[c(-3,-5,-2)]
 A  D  F  G  H  I  J 
 1  4  6  7  8  9 10 

Mixing does not work.

x[c(-3,1)]  # Will throw an error

R objects can have attributes

In a named vector, the names are an attribute.

x
 A  B  C  D  E  F  G  H  I  J 
 1  2  3  4  5  6  7  8  9 10 
attributes(x)
$names
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

Attributes can be assigned freely.

attr(x, "SayHi") <- "Hi"
attr(x, "SayBye") <- "Bye"
attributes(x)
$names
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

$SayHi
[1] "Hi"

$SayBye
[1] "Bye"

Attributes in data structures

library(nycflights13)
attributes(airports)
$class
[1] "tbl_df"     "tbl"        "data.frame"

$row.names
   [1]    1    2    3    4    5    6    7    8    9   10   11   12   13   14
  [15]   15   16   17   18   19   20   21   22   23   24   25   26   27   28
  [29]   29   30   31   32   33   34   35   36   37   38   39   40   41   42
  [43]   43   44   45   46   47   48   49   50   51   52   53   54   55   56
  [57]   57   58   59   60   61   62   63   64   65   66   67   68   69   70
  [71]   71   72   73   74   75   76   77   78   79   80   81   82   83   84
  [85]   85   86   87   88   89   90   91   92   93   94   95   96   97   98
  [99]   99  100  101  102  103  104  105  106  107  108  109  110  111  112
 [113]  113  114  115  116  117  118  119  120  121  122  123  124  125  126
 [127]  127  128  129  130  131  132  133  134  135  136  137  138  139  140
 [141]  141  142  143  144  145  146  147  148  149  150  151  152  153  154
 [155]  155  156  157  158  159  160  161  162  163  164  165  166  167  168
 [169]  169  170  171  172  173  174  175  176  177  178  179  180  181  182
 [183]  183  184  185  186  187  188  189  190  191  192  193  194  195  196
 [197]  197  198  199  200  201  202  203  204  205  206  207  208  209  210
 [211]  211  212  213  214  215  216  217  218  219  220  221  222  223  224
 [225]  225  226  227  228  229  230  231  232  233  234  235  236  237  238
 [239]  239  240  241  242  243  244  245  246  247  248  249  250  251  252
 [253]  253  254  255  256  257  258  259  260  261  262  263  264  265  266
 [267]  267  268  269  270  271  272  273  274  275  276  277  278  279  280
 [281]  281  282  283  284  285  286  287  288  289  290  291  292  293  294
 [295]  295  296  297  298  299  300  301  302  303  304  305  306  307  308
 [309]  309  310  311  312  313  314  315  316  317  318  319  320  321  322
 [323]  323  324  325  326  327  328  329  330  331  332  333  334  335  336
 [337]  337  338  339  340  341  342  343  344  345  346  347  348  349  350
 [351]  351  352  353  354  355  356  357  358  359  360  361  362  363  364
 [365]  365  366  367  368  369  370  371  372  373  374  375  376  377  378
 [379]  379  380  381  382  383  384  385  386  387  388  389  390  391  392
 [393]  393  394  395  396  397  398  399  400  401  402  403  404  405  406
 [407]  407  408  409  410  411  412  413  414  415  416  417  418  419  420
 [421]  421  422  423  424  425  426  427  428  429  430  431  432  433  434
 [435]  435  436  437  438  439  440  441  442  443  444  445  446  447  448
 [449]  449  450  451  452  453  454  455  456  457  458  459  460  461  462
 [463]  463  464  465  466  467  468  469  470  471  472  473  474  475  476
 [477]  477  478  479  480  481  482  483  484  485  486  487  488  489  490
 [491]  491  492  493  494  495  496  497  498  499  500  501  502  503  504
 [505]  505  506  507  508  509  510  511  512  513  514  515  516  517  518
 [519]  519  520  521  522  523  524  525  526  527  528  529  530  531  532
 [533]  533  534  535  536  537  538  539  540  541  542  543  544  545  546
 [547]  547  548  549  550  551  552  553  554  555  556  557  558  559  560
 [561]  561  562  563  564  565  566  567  568  569  570  571  572  573  574
 [575]  575  576  577  578  579  580  581  582  583  584  585  586  587  588
 [589]  589  590  591  592  593  594  595  596  597  598  599  600  601  602
 [603]  603  604  605  606  607  608  609  610  611  612  613  614  615  616
 [617]  617  618  619  620  621  622  623  624  625  626  627  628  629  630
 [631]  631  632  633  634  635  636  637  638  639  640  641  642  643  644
 [645]  645  646  647  648  649  650  651  652  653  654  655  656  657  658
 [659]  659  660  661  662  663  664  665  666  667  668  669  670  671  672
 [673]  673  674  675  676  677  678  679  680  681  682  683  684  685  686
 [687]  687  688  689  690  691  692  693  694  695  696  697  698  699  700
 [701]  701  702  703  704  705  706  707  708  709  710  711  712  713  714
 [715]  715  716  717  718  719  720  721  722  723  724  725  726  727  728
 [729]  729  730  731  732  733  734  735  736  737  738  739  740  741  742
 [743]  743  744  745  746  747  748  749  750  751  752  753  754  755  756
 [757]  757  758  759  760  761  762  763  764  765  766  767  768  769  770
 [771]  771  772  773  774  775  776  777  778  779  780  781  782  783  784
 [785]  785  786  787  788  789  790  791  792  793  794  795  796  797  798
 [799]  799  800  801  802  803  804  805  806  807  808  809  810  811  812
 [813]  813  814  815  816  817  818  819  820  821  822  823  824  825  826
 [827]  827  828  829  830  831  832  833  834  835  836  837  838  839  840
 [841]  841  842  843  844  845  846  847  848  849  850  851  852  853  854
 [855]  855  856  857  858  859  860  861  862  863  864  865  866  867  868
 [869]  869  870  871  872  873  874  875  876  877  878  879  880  881  882
 [883]  883  884  885  886  887  888  889  890  891  892  893  894  895  896
 [897]  897  898  899  900  901  902  903  904  905  906  907  908  909  910
 [911]  911  912  913  914  915  916  917  918  919  920  921  922  923  924
 [925]  925  926  927  928  929  930  931  932  933  934  935  936  937  938
 [939]  939  940  941  942  943  944  945  946  947  948  949  950  951  952
 [953]  953  954  955  956  957  958  959  960  961  962  963  964  965  966
 [967]  967  968  969  970  971  972  973  974  975  976  977  978  979  980
 [981]  981  982  983  984  985  986  987  988  989  990  991  992  993  994
 [995]  995  996  997  998  999 1000 1001 1002 1003 1004 1005 1006 1007 1008
[1009] 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
[1023] 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
[1037] 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
[1051] 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
[1065] 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
[1079] 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
[1093] 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
[1107] 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
[1121] 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
[1135] 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
[1149] 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
[1163] 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
[1177] 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
[1191] 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
[1205] 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
[1219] 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
[1233] 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
[1247] 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
[1261] 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
[1275] 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
[1289] 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
[1303] 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
[1317] 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
[1331] 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
[1345] 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
[1359] 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
[1373] 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
[1387] 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
[1401] 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
[1415] 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
[1429] 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
[1443] 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
[1457] 1457 1458

$spec
cols(
  id = col_double(),
  name = col_character(),
  city = col_character(),
  country = col_character(),
  faa = col_character(),
  icao = col_character(),
  lat = col_double(),
  lon = col_double(),
  alt = col_double(),
  tz = col_double(),
  dst = col_character(),
  tzone = col_character()
)

$names
[1] "faa"   "name"  "lat"   "lon"   "alt"   "tz"    "dst"   "tzone"

Three important attributes

  • Names are used to name element of a vector, also works for lists and therefore also data frames (lists of atomic vectors of the same length)
  • Dimensions (dim()) is a short numeric vector making a vector behave as a matrix or a higher dimensional array. A vector 1:6 together with dim being c(2,3) is a matrix with 2 rows and 3 columns
    \(\begin{bmatrix} 1 & 3 & 5 \\ 2 & 4 & 6 \end{bmatrix}\)
  • Class is used to implement the S3 object oriented system. We don’t need to know the details here. The class system makes it for example possible that the same function, e.g. print() behaves differently for objects of a different class.

Class plays a role in specifying augmented vectors like factors, dates, date-times, or tibbles.

Augmented vectors

Factors

R uses factors to handle categorical variables, variables that have a fixed and known set of possible values

x <- factor(c("BS", "MS", "PhD", "MS", "BS", "BS"))
x
[1] BS  MS  PhD MS  BS  BS 
Levels: BS MS PhD

Technically, a factor is vector of integers with a levels attribute which specifies the categories for the integers.

typeof(x)
[1] "integer"
as.integer(x)
[1] 1 2 3 2 1 1
attributes(x)
$levels
[1] "BS"  "MS"  "PhD"

$class
[1] "factor"

The class factor makes R print the level of each element of the vector instead of the underlying integer.

Factors for data visualization

We manipulate factors with functions from the forcats package of the tidyverse core.

mpg |> ggplot(aes(y = manufacturer)) + geom_bar()

mpg |> ggplot(aes(y = fct_rev(manufacturer))) + geom_bar()

mpg |> ggplot(aes(y = fct_rev(fct_infreq(manufacturer)))) + geom_bar()

mpg |> ggplot(aes(y = fct_other(manufacturer, keep = c("dodge", "toyota", "volkswagen")))) + geom_bar()

Dates

  • ISO 8601 standard for dates: YYYY-MM-DD. Today: 2023-12-04.
  • Dates in R are numeric vectors that represent the number of days since 1 January 1970.
y <- as.Date("2020-01-01"); y
[1] "2020-01-01"
typeof(y)
[1] "double"
attributes(y)
$class
[1] "Date"
as.double(y)
[1] 18262
as.double(as.Date("1970-01-01"))
[1] 0
as.double(as.Date("1969-01-01"))
[1] -365

How many days are you old?

Sys.Date() - as.Date("1976-01-16") 
Time difference of 17489 days
# Sys.Date() gives as the current day your computer is set to

Date-times

For date-time manipulation use lubridate form the tidyverse.

x <- lubridate::ymd_hm("1970-01-01 01:00")
# Note: Instead of loading package `pack` to use its function `func` you can also write `pack::func`
# This works when the package is installed even when not loaded.
x
[1] "1970-01-01 01:00:00 UTC"
attributes(x)
$class
[1] "POSIXct" "POSIXt" 

$tzone
[1] "UTC"
as.double(x)
[1] 3600

UTC: Coordinated Universal Time. We are in the UTC+1 timezone.
POSIXct: Portable Operating System Interface, calendar time. Stores date and time in seconds with the number of seconds beginning at 1 January 1970.

How many seconds are you old?

as.double(lubridate::now()) - 
 as.double(lubridate::ymd_hm("1976-01-16_12:04"))
[1] 1511006233

Summary on Factors and Dates

  • Factors
    • Can be used to create categorical variables specified by the levels-attribute
    • Often used to specify the order of categories. Particularly useful for graphics!
    • Can be manipulated with functions from the forcats package
    • Often it is sufficient to work with character vectors.
  • Dates and times
    • Do not shy away from learning to work with dates and times properly!
    • Tedious to get right when the date format from the data is messy, but it is worth it!
    • Use the lubridate package. Usually you just need one command to convert a character vector to a date or date-time vector, but you have to customize correctly.

Read the chapter of factors and dates in R for Data Science

Strings

String modification

We modify strings with the stringr package from the tidyverse core. All functions from stringr start with str_.

Very few examples:

c("x","y")
[1] "x" "y"
str_c("x","y")
[1] "xy"
str_c("x","y","z", sep=",")
[1] "x,y,z"
length(c("x","y","z"))
[1] 3
str_length(c("x","y","z"))
[1] 1 1 1
str_length(c("This is a string.","z"))
[1] 17  1

String wrangling with variable names

data <- tibble(Name = c("A","B","C"), Age_2020 = c(20,30,40), Age_2021 = c(21,31,41), Age_2022 = c(22,32,42))
data
# A tibble: 3 × 4
  Name  Age_2020 Age_2021 Age_2022
  <chr>    <dbl>    <dbl>    <dbl>
1 A           20       21       22
2 B           30       31       32
3 C           40       41       42

We tidy that data set by creating a year variable.

data |> pivot_longer(c("Age_2020", "Age_2021", "Age_2022"), names_to = "Year", values_to="Age")
# A tibble: 9 × 3
  Name  Year       Age
  <chr> <chr>    <dbl>
1 A     Age_2020    20
2 A     Age_2021    21
3 A     Age_2022    22
4 B     Age_2020    30
5 B     Age_2021    31
6 B     Age_2022    32
7 C     Age_2020    40
8 C     Age_2021    41
9 C     Age_2022    42

OK, but the year variable is a string but we want numbers.

Use word

word extracts words from a sentence. However, the separator need not be " " but can be any character.

word("This is a string.", start=2, end=-2) 
[1] "is a"
#Selects from the second to the second last word.
word("Age_2022", start=2, sep = "_")
[1] "2022"

It also works vectorized.

data |> pivot_longer(c("Age_2020", "Age_2021", "Age_2022"), names_to = "Year", values_to="Age") |> 
  mutate(Year = word(Year, start = 2, sep = "_") |> as.numeric())
# A tibble: 9 × 3
  Name   Year   Age
  <chr> <dbl> <dbl>
1 A      2020    20
2 A      2021    21
3 A      2022    22
4 B      2020    30
5 B      2021    31
6 B      2022    32
7 C      2020    40
8 C      2021    41
9 C      2022    42

String detection and regular expressions

fruits <- c("apple", "pineapple", "Pear", "orange", "peach", "banana")
str_detect(fruits,"apple")
[1]  TRUE  TRUE FALSE FALSE FALSE FALSE
str_extract(fruits,"apple")
[1] "apple" "apple" NA      NA      NA      NA     

Regular expressions are useful because strings usually contain unstructured or semi-structured data, and regexps are a concise language for describing patterns in strings. When you first look at a regexp, you’ll think a cat walked across your keyboard, but as your understanding improves they will start to make sense.

"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"

"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"

""^[[:alnum:].-_]+@[[:alnum:].-]+$""

These are all regular expressions for email addresses.

Special values

  • NA: Not available
  • NaN: Not a number
  • Inf: Positive infinity
  • -Inf: Negative infinity
1/0
[1] Inf
-1/0
[1] -Inf
0/0
[1] NaN
1/0 + 1/0
[1] Inf
1/0 - 1/0
[1] NaN

NAs

Instead of NaN, NA stands for genuinely unknown values.
It can also be in a character of logical vector.

x = c(1, 2, 3, 4, NA)
mean(x)
[1] NA
mean(x, na.rm = TRUE)
[1] 2.5
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
   1.00    1.75    2.50    2.50    3.25    4.00       1 

The type of NA is logical.

typeof(NA)
[1] "logical"
typeof(NaN)
[1] "double"

Does it make sense?

NAs in logical operations

NA can be TRUE or FALSE.

Usually operations including NA results again in NA, but some not!

NA & TRUE
[1] NA
NA | TRUE
[1] TRUE
NA & FALSE
[1] FALSE
NA | FALSE
[1] NA

Understanding logical operations is important!

NULL is the null object

  • used to represent lists with zero length
x <- 1:10
attributes(x)
NULL
  • used as a placeholder for missing values in lists and data frames
L <- list(a = 1)
L[[3]] <- 5
L
$a
[1] 1

[[2]]
NULL

[[3]]
[1] 5

Relational Data

Working with more data frames

  • Data can be distributed in several data frames which have relations which each other.
  • For example, they share variables as the five data frames in nycflights13.

Data: Women in science

10 women in science who changed the world: Ada Lovelace, Marie Curie, Janaki Ammal, Chien-Shiung Wu, Katherine Johnson, Rosalind Franklin, Vera Rubin, Gladys West, Flossie Wong-Staal, Jennifer Doudna

professions <- read_csv("data/scientists/professions.csv")
professions
# A tibble: 10 × 2
   name               profession                        
   <chr>              <chr>                             
 1 Ada Lovelace       Mathematician                     
 2 Marie Curie        Physicist and Chemist             
 3 Janaki Ammal       Botanist                          
 4 Chien-Shiung Wu    Physicist                         
 5 Katherine Johnson  Mathematician                     
 6 Rosalind Franklin  Chemist                           
 7 Vera Rubin         Astronomer                        
 8 Gladys West        Mathematician                     
 9 Flossie Wong-Staal Virologist and Molecular Biologist
10 Jennifer Doudna    Biochemist                        
dates <- read_csv("data/scientists/dates.csv")
dates
# A tibble: 8 × 3
  name               birth_year death_year
  <chr>                   <dbl>      <dbl>
1 Janaki Ammal             1897       1984
2 Chien-Shiung Wu          1912       1997
3 Katherine Johnson        1918       2020
4 Rosalind Franklin        1920       1958
5 Vera Rubin               1928       2016
6 Gladys West              1930         NA
7 Flossie Wong-Staal       1947         NA
8 Jennifer Doudna          1964         NA
works <- read_csv("data/scientists/works.csv")
works
# A tibble: 9 × 2
  name               known_for                                                  
  <chr>              <chr>                                                      
1 Ada Lovelace       first computer algorithm                                   
2 Marie Curie        theory of radioactivity,  discovery of elements polonium a…
3 Janaki Ammal       hybrid species, biodiversity protection                    
4 Chien-Shiung Wu    confim and refine theory of radioactive beta decy, Wu expe…
5 Katherine Johnson  calculations of orbital mechanics critical to sending the …
6 Vera Rubin         existence of dark matter                                   
7 Gladys West        mathematical modeling of the shape of the Earth which serv…
8 Flossie Wong-Staal first scientist to clone HIV and create a map of its genes…
9 Jennifer Doudna    one of the primary developers of CRISPR, a ground-breaking…

We want this data frame

# A tibble: 10 × 5
   name               profession                 birth_year death_year known_for
   <chr>              <chr>                           <dbl>      <dbl> <chr>    
 1 Ada Lovelace       Mathematician                      NA         NA first co…
 2 Marie Curie        Physicist and Chemist              NA         NA theory o…
 3 Janaki Ammal       Botanist                         1897       1984 hybrid s…
 4 Chien-Shiung Wu    Physicist                        1912       1997 confim a…
 5 Katherine Johnson  Mathematician                    1918       2020 calculat…
 6 Rosalind Franklin  Chemist                          1920       1958 <NA>     
 7 Vera Rubin         Astronomer                       1928       2016 existenc…
 8 Gladys West        Mathematician                    1930         NA mathemat…
 9 Flossie Wong-Staal Virologist and Molecular …       1947         NA first sc…
10 Jennifer Doudna    Biochemist                       1964         NA one of t…

Joining data frames

something_join(x, y)1 for data frames x and y which have a relation

  • left_join(): all rows from x
  • right_join(): all rows from y
  • full_join(): all rows from both x and y
  • inner_join(): all rows from x where there are matching values in y, return all combination of multiple matches in the case of multiple matches

Simple setup for x and y

x <- tibble(
  id = c(1, 2, 3),
  value_x = c("x1", "x2", "x3")
  )
y <- tibble(
  id = c(1, 2, 4),
  value_y = c("y1", "y2", "y4")
  )
x
# A tibble: 3 × 2
     id value_x
  <dbl> <chr>  
1     1 x1     
2     2 x2     
3     3 x3     
y
# A tibble: 3 × 2
     id value_y
  <dbl> <chr>  
1     1 y1     
2     2 y2     
3     4 y4     

left_join()

left_join(x, y)
# A tibble: 3 × 3
     id value_x value_y
  <dbl> <chr>   <chr>  
1     1 x1      y1     
2     2 x2      y2     
3     3 x3      <NA>   

right_join()

right_join(x, y)
# A tibble: 3 × 3
     id value_x value_y
  <dbl> <chr>   <chr>  
1     1 x1      y1     
2     2 x2      y2     
3     4 <NA>    y4     

full_join()

full_join(x, y)
# A tibble: 4 × 3
     id value_x value_y
  <dbl> <chr>   <chr>  
1     1 x1      y1     
2     2 x2      y2     
3     3 x3      <NA>   
4     4 <NA>    y4     

inner_join()

inner_join(x, y)
# A tibble: 2 × 3
     id value_x value_y
  <dbl> <chr>   <chr>  
1     1 x1      y1     
2     2 x2      y2     

Women in science

professions |> left_join(works)
# A tibble: 10 × 3
   name               profession                         known_for              
   <chr>              <chr>                              <chr>                  
 1 Ada Lovelace       Mathematician                      first computer algorit…
 2 Marie Curie        Physicist and Chemist              theory of radioactivit…
 3 Janaki Ammal       Botanist                           hybrid species, biodiv…
 4 Chien-Shiung Wu    Physicist                          confim and refine theo…
 5 Katherine Johnson  Mathematician                      calculations of orbita…
 6 Rosalind Franklin  Chemist                            <NA>                   
 7 Vera Rubin         Astronomer                         existence of dark matt…
 8 Gladys West        Mathematician                      mathematical modeling …
 9 Flossie Wong-Staal Virologist and Molecular Biologist first scientist to clo…
10 Jennifer Doudna    Biochemist                         one of the primary dev…
professions |> right_join(works)
# A tibble: 9 × 3
  name               profession                         known_for               
  <chr>              <chr>                              <chr>                   
1 Ada Lovelace       Mathematician                      first computer algorithm
2 Marie Curie        Physicist and Chemist              theory of radioactivity…
3 Janaki Ammal       Botanist                           hybrid species, biodive…
4 Chien-Shiung Wu    Physicist                          confim and refine theor…
5 Katherine Johnson  Mathematician                      calculations of orbital…
6 Vera Rubin         Astronomer                         existence of dark matter
7 Gladys West        Mathematician                      mathematical modeling o…
8 Flossie Wong-Staal Virologist and Molecular Biologist first scientist to clon…
9 Jennifer Doudna    Biochemist                         one of the primary deve…
dates |> full_join(works)
# A tibble: 10 × 4
   name               birth_year death_year known_for                           
   <chr>                   <dbl>      <dbl> <chr>                               
 1 Janaki Ammal             1897       1984 hybrid species, biodiversity protec…
 2 Chien-Shiung Wu          1912       1997 confim and refine theory of radioac…
 3 Katherine Johnson        1918       2020 calculations of orbital mechanics c…
 4 Rosalind Franklin        1920       1958 <NA>                                
 5 Vera Rubin               1928       2016 existence of dark matter            
 6 Gladys West              1930         NA mathematical modeling of the shape …
 7 Flossie Wong-Staal       1947         NA first scientist to clone HIV and cr…
 8 Jennifer Doudna          1964         NA one of the primary developers of CR…
 9 Ada Lovelace               NA         NA first computer algorithm            
10 Marie Curie                NA         NA theory of radioactivity,  discovery…
dates |> inner_join(works)
# A tibble: 7 × 4
  name               birth_year death_year known_for                            
  <chr>                   <dbl>      <dbl> <chr>                                
1 Janaki Ammal             1897       1984 hybrid species, biodiversity protect…
2 Chien-Shiung Wu          1912       1997 confim and refine theory of radioact…
3 Katherine Johnson        1918       2020 calculations of orbital mechanics cr…
4 Vera Rubin               1928       2016 existence of dark matter             
5 Gladys West              1930         NA mathematical modeling of the shape o…
6 Flossie Wong-Staal       1947         NA first scientist to clone HIV and cre…
7 Jennifer Doudna          1964         NA one of the primary developers of CRI…
professions |> left_join(dates) |> left_join(works)
# A tibble: 10 × 5
   name               profession                 birth_year death_year known_for
   <chr>              <chr>                           <dbl>      <dbl> <chr>    
 1 Ada Lovelace       Mathematician                      NA         NA first co…
 2 Marie Curie        Physicist and Chemist              NA         NA theory o…
 3 Janaki Ammal       Botanist                         1897       1984 hybrid s…
 4 Chien-Shiung Wu    Physicist                        1912       1997 confim a…
 5 Katherine Johnson  Mathematician                    1918       2020 calculat…
 6 Rosalind Franklin  Chemist                          1920       1958 <NA>     
 7 Vera Rubin         Astronomer                       1928       2016 existenc…
 8 Gladys West        Mathematician                    1930         NA mathemat…
 9 Flossie Wong-Staal Virologist and Molecular …       1947         NA first sc…
10 Jennifer Doudna    Biochemist                       1964         NA one of t…

Keys

  • A key is a variable or a set of variables which uniquely identifies observations
  • What was the key in the data frame of women in science?
  • Switching back to nycflights13 as example
  • In simple cases, a single variable is sufficient to identify an observation, e.g. each plane in planes is identified by tailnum.
  • Sometimes, multiple variables are needed; e.g. to identify an observation in weather you need five variables: year, month, day, hour, and origin

How can we check?

Counting observation and filter those more than one

library(nycflights13)
planes |> count(tailnum) |> filter(n > 1)
# A tibble: 0 × 2
# ℹ 2 variables: tailnum <chr>, n <int>
weather |> count(year, month, day, hour, origin) |> filter(n > 1) 
# A tibble: 3 × 6
   year month   day  hour origin     n
  <int> <int> <int> <int> <chr>  <int>
1  2013    11     3     1 EWR        2
2  2013    11     3     1 JFK        2
3  2013    11     3     1 LGA        2
# OK, here 3 observations are twice. Probably a data error.
# Example: Without hour it is not a key
weather |> count(year, month, day, origin) |> filter(n > 1) 
# A tibble: 1,092 × 5
    year month   day origin     n
   <int> <int> <int> <chr>  <int>
 1  2013     1     1 EWR       22
 2  2013     1     1 JFK       22
 3  2013     1     1 LGA       23
 4  2013     1     2 EWR       24
 5  2013     1     2 JFK       24
 6  2013     1     2 LGA       24
 7  2013     1     3 EWR       24
 8  2013     1     3 JFK       24
 9  2013     1     3 LGA       24
10  2013     1     4 EWR       24
# ℹ 1,082 more rows

Terminology: Primary and foreign keys

  • A primary key uniquely identifies an observation in its own table. E.g, planes$tailnum in planes.

  • A foreign key uniquely identifies an observation in another data frame E.g. flights$tailnum is a foreign key in flights because it matches each flight to a unique plane in planes.

  • Data frames need not have a key and the joins will still do their work.

  • A primary key and a foreign key form a relation.

  • Relations are typically 1-to-many. Each plane has many flights

  • Relations can also be many-to-many. Airlines can fly to many airports; airport can host many airplanes.

Joining when key names differ?

We have to specify the key relation with a named vector in the by argument.

dim(flights)
[1] 336776     19
flights |> left_join(airports, by = c("dest" = "faa"))
# A tibble: 336,776 × 26
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>
 1  2013     1     1      517            515         2      830            819
 2  2013     1     1      533            529         4      850            830
 3  2013     1     1      542            540         2      923            850
 4  2013     1     1      544            545        -1     1004           1022
 5  2013     1     1      554            600        -6      812            837
 6  2013     1     1      554            558        -4      740            728
 7  2013     1     1      555            600        -5      913            854
 8  2013     1     1      557            600        -3      709            723
 9  2013     1     1      557            600        -3      838            846
10  2013     1     1      558            600        -2      753            745
# ℹ 336,766 more rows
# ℹ 18 more variables: arr_delay <dbl>, carrier <chr>, flight <int>,
#   tailnum <chr>, origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>,
#   hour <dbl>, minute <dbl>, time_hour <dttm>, name <chr>, lat <dbl>,
#   lon <dbl>, alt <dbl>, tz <dbl>, dst <chr>, tzone <chr>
# New version
flights |> left_join(airports, join_by("dest" == "faa"))
# A tibble: 336,776 × 26
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>
 1  2013     1     1      517            515         2      830            819
 2  2013     1     1      533            529         4      850            830
 3  2013     1     1      542            540         2      923            850
 4  2013     1     1      544            545        -1     1004           1022
 5  2013     1     1      554            600        -6      812            837
 6  2013     1     1      554            558        -4      740            728
 7  2013     1     1      555            600        -5      913            854
 8  2013     1     1      557            600        -3      709            723
 9  2013     1     1      557            600        -3      838            846
10  2013     1     1      558            600        -2      753            745
# ℹ 336,766 more rows
# ℹ 18 more variables: arr_delay <dbl>, carrier <chr>, flight <int>,
#   tailnum <chr>, origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>,
#   hour <dbl>, minute <dbl>, time_hour <dttm>, name <chr>, lat <dbl>,
#   lon <dbl>, alt <dbl>, tz <dbl>, dst <chr>, tzone <chr>

Why does the number of rows stays the same after joining?

faa is a primary key in airports.

left_join essentially right_join with switched data frames

airports_right_flights <- airports |> right_join(flights, by = c("faa" = "dest"))
airports_right_flights 
# A tibble: 336,776 × 26
   faa   name       lat   lon   alt    tz dst   tzone  year month   day dep_time
   <chr> <chr>    <dbl> <dbl> <dbl> <dbl> <chr> <chr> <int> <int> <int>    <int>
 1 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     1     1955
 2 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     2     2010
 3 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     3     1955
 4 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     4     2017
 5 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     5     1959
 6 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     6     1959
 7 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     7     2002
 8 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     8     1957
 9 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10     9     1957
10 ABQ   Albuque…  35.0 -107.  5355    -7 A     Amer…  2013    10    10     2011
# ℹ 336,766 more rows
# ℹ 14 more variables: sched_dep_time <int>, dep_delay <dbl>, arr_time <int>,
#   sched_arr_time <int>, arr_delay <dbl>, carrier <chr>, flight <int>,
#   tailnum <chr>, origin <chr>, air_time <dbl>, distance <dbl>, hour <dbl>,
#   minute <dbl>, time_hour <dttm>

Differences

  • In a join where keys have different column names the name of the first data frame survives (unless you use keep = TRUE). Here, faa instead of dest
  • The columns from the first data frame come first
  • The order of rows is taken from the first data frame, while duplication and dropping of variables is determined by the second data frame (because it is a right_join)

Using the fact that flights seem to be ordered by year, month, day, dep_time we can re-arrange:

airports_right_flights |> 
  rename(dest = faa) |> 
  select(names(flights)) |> # Use order of flights
  arrange(year, month, day, dep_time)
# A tibble: 336,776 × 19
    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time
   <int> <int> <int>    <int>          <int>     <dbl>    <int>          <int>
 1  2013     1     1      517            515         2      830            819
 2  2013     1     1      533            529         4      850            830
 3  2013     1     1      542            540         2      923            850
 4  2013     1     1      544            545        -1     1004           1022
 5  2013     1     1      554            600        -6      812            837
 6  2013     1     1      554            558        -4      740            728
 7  2013     1     1      555            600        -5      913            854
 8  2013     1     1      557            600        -3      709            723
 9  2013     1     1      557            600        -3      838            846
10  2013     1     1      558            600        -2      924            917
# ℹ 336,766 more rows
# ℹ 11 more variables: arr_delay <dbl>, carrier <chr>, flight <int>,
#   tailnum <chr>, origin <chr>, dest <chr>, air_time <dbl>, distance <dbl>,
#   hour <dbl>, minute <dbl>, time_hour <dttm>

Note of caution: A deeper analysis shows that the order is still not exactly the same.

left_join with reversed data frames

dim(airports)
[1] 1458    8
dim(flights)
[1] 336776     19
airports |> 
  left_join(flights, by = c("faa" = "dest"))
# A tibble: 330,531 × 26
   faa   name      lat    lon   alt    tz dst   tzone  year month   day dep_time
   <chr> <chr>   <dbl>  <dbl> <dbl> <dbl> <chr> <chr> <int> <int> <int>    <int>
 1 04G   Lansdo…  41.1  -80.6  1044    -5 A     Amer…    NA    NA    NA       NA
 2 06A   Moton …  32.5  -85.7   264    -6 A     Amer…    NA    NA    NA       NA
 3 06C   Schaum…  42.0  -88.1   801    -6 A     Amer…    NA    NA    NA       NA
 4 06N   Randal…  41.4  -74.4   523    -5 A     Amer…    NA    NA    NA       NA
 5 09J   Jekyll…  31.1  -81.4    11    -5 A     Amer…    NA    NA    NA       NA
 6 0A9   Elizab…  36.4  -82.2  1593    -5 A     Amer…    NA    NA    NA       NA
 7 0G6   Willia…  41.5  -84.5   730    -5 A     Amer…    NA    NA    NA       NA
 8 0G7   Finger…  42.9  -76.8   492    -5 A     Amer…    NA    NA    NA       NA
 9 0P2   Shoest…  39.8  -76.6  1000    -5 U     Amer…    NA    NA    NA       NA
10 0S9   Jeffer…  48.1 -123.    108    -8 A     Amer…    NA    NA    NA       NA
# ℹ 330,521 more rows
# ℹ 14 more variables: sched_dep_time <int>, dep_delay <dbl>, arr_time <int>,
#   sched_arr_time <int>, arr_delay <dbl>, carrier <chr>, flight <int>,
#   tailnum <chr>, origin <chr>, air_time <dbl>, distance <dbl>, hour <dbl>,
#   minute <dbl>, time_hour <dttm>

Why does the number of rows changes after joining?

dest is not a primary key in flights. There are more flights with the same destination so rows of airports get duplicated.

Why is the number of rows then less than the number of rows in flights?

Let us do some checks:

length(unique(airports$faa)) # Unique turns out to be redundant because faa is a primary key
[1] 1458
length(unique(flights$dest))
[1] 105
# There are much more airports then destinations in flights!
# ... but the rows of airports prevail when it is the first in a left_join.
# So, the data frame should even increase because 
# we get several rows of airports without flights
# Let us dig deeper.

setdiff( unique(airports$faa), unique(flights$dest)) |> length()
[1] 1357
# 1,357 airports have no flights. But also:
setdiff( unique(flights$dest), unique(airports$faa)) |> length()
[1] 4
# There are four destinations in flights, which are not in the airports list!

# How many flights are to these?
flights |> 
  filter(dest %in% setdiff( unique(flights$dest), unique(airports$faa))) |> 
  nrow()
[1] 7602
# 7,602 flights go to destinations not listed as airport

# Check
nrow(airports |> left_join(flights, by = c("faa" = "dest"))) == nrow(flights) - 7602 + 1357
[1] TRUE
# OK, now we have a clear picture
# airport with left_joined flights duplicates the rows an airports for each flight flying to it
# So the total number of rows is the number of flights plus the number of airport which do not 
# appear as a destination minus the flights which go to destinations which are not listed in airports

Learning: The new number of observation after a join can be a complex combination of duplication and dropping. It is your responsibility to understand what is happening.

Next Steps

  • This and next week: Introduction to python

  • Then you should be able to do wrangle, transform, and basically visualize data how you want. (Usually some self-study is necessary when new problems pop up. )

  • Expect and update of a few questions in Homework 2 for exploratory data analysis.