W#03 Data Import, Data Wrangling

With material adopted from Data Science in a Box and R4DS

Jan Lorenz

Data Import, First Look

readr and readxl

readr is loaded with tidyverse

  • 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

readxl has to be installed and loaded separately

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

Importing data from other sources

R packages for some cases. They provide function to read from the source into dataframes.

  • Data collected in a Google Spreadsheet: googlesheets4
  • Data in native formats of SPSS, Stata, or SAS: haven
  • Data in SQL Databases: DBI, together with a database specific backend (RMySQL, RSQLite, RPostgreSQL)
  • Data in JSON or XML format as often used by web applications (e.g. written in JavaScript): jsonlite and xml2
  • Scraping data directly from websites: rvest
  • Using Appache Arrow, e.g. .parquet files: arrow

Comma-separated values (CSV)

CSV files are delimited text file

  • Can be viewed with any text editor
  • Show each row of the dataframe 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!

We use CSV file when there is no certain reason to do otherwise. Reasons are: CSV is not provided or the dataset being very larger and hard-disk storage is an issue. Other formats or more space efficient.

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.

library(tidyverse)
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 dataframe

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

Wrangling = Import + Tidy + Transform (first iteration)

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 dataframes 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 dataframe (tibble) as first argument
  • outputs a (manipulated) dataframe (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 dataframe 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
  • 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)
delivers the same. (Spot the tiny difference!)

filter for more complex 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
!x not x

Test these (vectors of) logical statements

c(2 == 2   ,   2 == 3) 
[1]  TRUE FALSE
c(2 != 2   ,    2 != 3) 
[1] FALSE  TRUE
c(2 != 2 & 2 != 3   ,   2 != 2 | 2 != 3)
[1] FALSE  TRUE
c(2 == 2   ,   !(2 == 2))
[1]  TRUE FALSE
c(2 != 2   ,    !(2 != 2))
[1] FALSE  TRUE

Numerical and Logical Indexing

The Concept of Indexing

Select and filter can also be achieved by numerical 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}\)

Logical Indexing

Instead of numerical indexing (with a vector of numbers) you can also use logical indexing with a vector of logicals.

With logical vectors you can select rows and columns.

We create a small sample data frame

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    

Now, we select some rows and a column with logical index vectors

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    

Counting and Sorting

Unique combinations, arranging

distinct and arrange (for sorting)

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

Counting, arrange descending

count, arrange, desc

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

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 dataframe 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()

Grouping alternative

Instead of a group_by(...) you can also use the .by = ... argument in summarize (or mutate)

hotels |>
  summarise(mean_adr = mean(adr), .by = c(hotel, arrival_date_week_number)) |> 
  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: Names vectors, Indexing

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 dataframes (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 and Dates

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: 2024-10-08.
  • 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 17798 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] 1537756533

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