Session 2: Data Wrangling with Tidyverse

Bella Ratmelia & Wei Xia

Today’s Outline

  1. Loading our data into RStudio environment
  2. Data wrangling with dplyr and tidyr (part of the tidyverse package)

Checklist when you start RStudio

  1. Go to the folder where you put your project for this workshop

  2. Find a file with .Rproj extension - this is the R project file that holds all the information about your project.

  1. Double click on the file. Rstudio should launch with your project loaded!

  2. Re-run the library(tidyverse) and read_csv portion in the previous session (the code is also on the next slide if you missed last week’s session)

Optional (Though best practice):

  • Make sure that Environment panel is empty (click on broom icon to clean it up).
  • Clear the Console and Plots too.

Refresher: Loading from CSV into a dataframe

Use read_csv from readr package (part of tidyverse) to load our World Values Survey data. More information about the data can be found under the Dataset tab in the course website.

# import tidyverse library
library(tidyverse)

# read the CSV and save into a dataframe called wvs_data
wvs_data <- read_csv("data/wvs-4-countries.csv")

# "peek" at the data, pay attention to the data types!
glimpse(wvs_data)

What do I need to know before we begin?

  • Always examine your data first (glimpse(), summary(), str()) before cleaning.
  • Never overwrite your raw data files
  • Budget extra time for data cleaning - it almost always takes longer than expected!
  • Having a clear understanding of the desired data shape is essential as real data often differs from what you imagine! Refer to codebook, actual questionnaire, appendix for guidance.
  • Look out for outliers!
  • Remember: Data cleaning techniques differ based on the problems, data type, and the research questions you are trying to answer. Various methods are available, each with its own trade-offs.

The tools we’re going to use: dplyr and tidyr from tidyverse

  • drop_na() - remove rows with missing values
  • select() - pick columns
  • filter() - pick rows based on criteria
  • mutate() - create or edit columns
  • if_else() / case_when() - used inside mutate() to set values based on conditions
  • group_by() + summarize() - group data and summarize each group

More advanced ones which is not covered in the workshop (see appendix for examples)

  • Joining multiple dataframes’ columns: left_join(), right_join(), inner_join(), full_join()

  • Joining multiple dataframes’ rows: bind_rows()

  • Splitting or combining cells: unite(), separate_wider_delim(), separate_long_delim()

Additionally: you may need the forcats cheatsheet here: https://raw.githubusercontent.com/rstudio/cheatsheets/main/factors.pdf

forcats is also part of tidyverse, specifically used to handle factor data.

Why are we using tidyverse? Is it a must?

It’s not a must, but it’ll be make our job much easier! Key advantages:

  • More ‘English’ looking code and thus more intuitive for beginners
  • Tidyverse follow consistent syntax patterns - first argument is always the data to work on, followed by the function name i.e the things that we want to do on to the data.
  • Tidyverse gives clearer, more helpful error messages

Example:

# Base R
subset_data <- data[data$age > 18 & data$income > 50000, c("name", "age", "salary")]

# Tidyverse  
subset_data <- data |> 
  filter(age > 18 & income > 50000)  |> 
  select(name, age, salary)

Scenario: Data wrangling activities with WVS data

We’re research assistants preparing WVS data from 4 countries (Hong Kong SAR, Indonesia, Malaysia, Turkey) for analysis.

  1. Remove all rows with missing values (NA)
  2. Check for duplicates
  3. Select only the relevant columns
  4. Filter for respondents aged 18 or older, and sort by age
  5. Create avg_satisfaction: the average of life_satisfaction and financial_satisfaction
  6. Create age groups for each generation: “18-28”, “29-44”, “45-60”, “61+”

Let’s wrangle our data!

Step #1

A strategy I’d like to recommend: briefly read over the dplyr cheatsheet and tidyr cheatsheet, and have them open on a separate tab so that you can refer to them quickly.

Remove rows with empty values (NA) with drop_na(). But first, how many rows would we lose?

nrow(wvs_data) # before
wvs_data |> drop_na() |> nrow() # drop rows missing ANY column
wvs_data |> drop_na(life_satisfaction) |> nrow() # drop rows missing life_satisfaction only
[1] 5252
[1] 5064
[1] 5244

Why might dropping every incomplete row be a bad idea?

For this workshop, we’ll keep things simple and drop all incomplete rows:

wvs_data <- wvs_data |>
  drop_na()

The number of observations after removing NAs:

dim(wvs_data)
[1] 5064   15

Interlude: Pipe Operator ( |> )

  • The pipe operator (|>) allows us to chain multiple operations without creating intermediate / temporary dataframes.

  • Super handy when we perform several data wrangling tasks using tidyverse in sequence.

  • Helps with readability, especially for complex operations.

  • Keyboard shortcut: Ctrl+Shift+M on Windows, Cmd+Shift+M on Mac

Notice that we have to create a “temp” dataframe called wvs_data_clean in this method.

wvs_data <- drop_na(wvs_data)
wvs_data_clean <- arrange(wvs_data, desc(age))
write_csv(wvs_data_clean, "data-output/wvs-clean.csv")

No “temporary” dataframe needed here! :D

wvs_data |>
    drop_na() |>
    distinct(respondent_id, .keep_all = TRUE) |>
    write_csv("data-output/wvs-clean.csv")

Step #2

Check for duplicates with distinct()

wvs_data <- wvs_data |>
  distinct(respondent_id, .keep_all = TRUE)

(Our data has no duplicates, but this is still a good practice to do, especially if we were combining data from multipe sources)

Step #3:

Select only the relevant columns: respondent_id, demographic columns, and attitudinal columns.

We can achieve this with select()!

wvs_data <- wvs_data |>
    select(respondent_id, country, sex, age, urban_rural, income_level,
           marital_status, education, life_satisfaction, freedom_of_choice,
           financial_satisfaction, trust_people, importance_of_god,
           emancipative_values, secular_values)

Preview of the filtered data:

Rows: 5,064
Columns: 15
$ respondent_id          <dbl> 344000109, 344000036, 344000445, 344001032, 344~
$ country                <chr> "Hong Kong SAR", "Hong Kong SAR", "Hong Kong SA~
$ sex                    <chr> "Female", "Female", "Female", "Female", "Female~
$ age                    <dbl> 28, 35, 52, 21, 30, 56, 46, 38, 25, 45, 55, 50,~
$ urban_rural            <chr> "Urban", "Urban", "Urban", "Urban", "Urban", "U~
$ income_level           <chr> "Medium", "Medium", "High", "Low", "Low", "Medi~
$ marital_status         <chr> "Single", "Married", "Single", "Single", "Singl~
$ education              <chr> "Middle", "Higher", "Higher", "Higher", "Middle~
$ life_satisfaction      <dbl> 8, 7, 9, 3, 8, 8, 6, 7, 7, 8, 6, 8, 7, 7, 7, 7,~
$ freedom_of_choice      <dbl> 8, 7, 8, 5, 8, 8, 6, 8, 7, 10, 6, 8, 7, 7, 7, 7~
$ financial_satisfaction <dbl> 8, 5, 9, 3, 3, 8, 6, 1, 7, 8, 7, 6, 5, 5, 7, 6,~
$ trust_people           <chr> "Trusted", "Not trusted", "Not trusted", "Not t~
$ importance_of_god      <dbl> 6, 2, 9, 8, 1, 8, 8, 5, 1, 8, 1, 8, 10, 1, 8, 1~
$ emancipative_values    <dbl> 0.6334, 0.4518, 0.5116, 0.6308, 0.3768, 0.3343,~
$ secular_values         <dbl> 0.4046, 0.4742, 0.5538, 0.1280, 0.3842, 0.4358,~

Renaming columns with rename()

Real survey exports often have long or messy column names. rename() uses the pattern new_name = old_name:

wvs_data |>
    rename(satisfaction = life_satisfaction) |>
    select(respondent_id, satisfaction) |>
    print(n = 3)
# A tibble: 5,064 x 2
  respondent_id satisfaction
          <dbl>        <dbl>
1     344000109            8
2     344000036            7
3     344000445            9
# i 5,061 more rows

(We’re not saving this result, so the column is still called life_satisfaction.)

Step #4:

Filter for respondents aged 18 or older. Optionally, we can then arrange the dataset by age (oldest to youngest)

wvs_data <- wvs_data |> 
    filter(age >= 18) |> 
    arrange(desc(age))

Checking the structure:

# A tibble: 6 x 15
  respondent_id country      sex     age urban_rural income_level marital_status
          <dbl> <chr>        <chr> <dbl> <chr>       <chr>        <chr>         
1     792000461 Turkey       Male     95 Urban       Medium       Married       
2     792001320 Turkey       Male     95 Urban       Medium       Widowed       
3     344001151 Hong Kong S~ Male     91 Urban       Low          Married       
4     344000263 Hong Kong S~ Fema~    89 Urban       Medium       Living togeth~
5     344000655 Hong Kong S~ Male     88 Urban       Medium       Divorced      
6     344000022 Hong Kong S~ Male     88 Urban       Low          Divorced      
# i 8 more variables: education <chr>, life_satisfaction <dbl>,
#   freedom_of_choice <dbl>, financial_satisfaction <dbl>, trust_people <chr>,
#   importance_of_god <dbl>, emancipative_values <dbl>, secular_values <dbl>

Filtering for several values with %in%

To keep rows that match any value in a list, use %in% inside filter(). It’s much easier to read than chaining |:

# same as: filter(country == "Indonesia" | country == "Malaysia")
wvs_data |>
    filter(country %in% c("Indonesia", "Malaysia")) |>
    distinct(country)
# A tibble: 2 x 1
  country  
  <chr>    
1 Indonesia
2 Malaysia 

(We’re not saving this result, so wvs_data still has all four countries.)

Step #5

Create a new column avg_satisfaction that averages life_satisfaction and financial_satisfaction as a combined wellbeing indicator.

We can achieve this with mutate()! (mutate() is to change or add new columns.)

wvs_data <- wvs_data |>
    mutate(avg_satisfaction = (life_satisfaction + financial_satisfaction) / 2)

Preview of the new column alongside the original ones:

# A tibble: 5,064 x 3
  life_satisfaction financial_satisfaction avg_satisfaction
              <dbl>                  <dbl>            <dbl>
1                 7                      8              7.5
2                 4                      4              4  
3                 5                      5              5  
4                 8                     10              9  
5                 6                      7              6.5
# i 5,059 more rows

Step #6

Create age groups for each generation: “18-28”, “29-44”, “45-60”, “61+”

wvs_data <- wvs_data |>
    mutate(age_group = case_when(
        age <= 28 ~ "18-28",
        age <= 44 ~ "29-44",
        age <= 60 ~ "45-60",
        TRUE ~ "61+"
    ))

Preview of age groups:

# A tibble: 5,064 x 2
    age age_group
  <dbl> <chr>    
1    95 61+      
2    95 61+      
3    91 61+      
4    89 61+      
# i 5,060 more rows

Checkpoint 1 - saving our hard work into a CSV file

We have done some cleaning! Let’s save this cleaned data into a separate CSV file called “wvs_cleaned_v1.csv”

wvs_data |> write_csv("data-output/wvs_cleaned_v1.csv")

Check the data output folder to make sure the CSV is created!

Simple descriptive analysis

Once we are done with the wrangling part, we can proceed with simple descriptive analysis!

  • Prep: Before we proceed further, convert the appropriate categorical variables (country, sex, marital_status, urban_rural, income_level, education, trust_people) to Factor

  • Analysis 1: Generate summary statistics of life_satisfaction grouped by country

  • Analysis 2: Create a new column called satisfaction_group that indicate whether each respondent has higher or lower than average life_satisfaction

  • Analysis 3: Reshape the data to show average satisfaction scores by country and age group

Prep before analysis: convert to factors

Let’s use the wvs_cleaned dataframe for this task.

We can do this with mutate() and as_factor() from forcats, another sub-package within tidyverse.

wvs_cleaned <- read_csv("data-output/wvs_cleaned_v1.csv")
wvs_cleaned <- wvs_cleaned |>
    mutate(
        country = as_factor(country),
        sex = as_factor(sex),
        marital_status = as_factor(marital_status),
        urban_rural = as_factor(urban_rural),
        income_level = as_factor(income_level),
        education = as_factor(education),
        trust_people = as_factor(trust_people)
    )

# check conversion result
str(wvs_cleaned)

Rstudio may auto-suggest as.factor() from base R. You can use this as well, but as_factor() is preferred since we are using tidyverse approach.

Prep before analysis: convert to factors

tibble [5,064 x 17] (S3: tbl_df/tbl/data.frame)
 $ respondent_id         : num [1:5064] 7.92e+08 7.92e+08 3.44e+08 3.44e+08 3.44e+08 ...
 $ country               : Factor w/ 4 levels "Turkey","Hong Kong SAR",..: 1 1 2 2 2 2 2 2 2 2 ...
 $ sex                   : Factor w/ 2 levels "Male","Female": 1 1 1 2 1 1 1 1 1 1 ...
 $ age                   : num [1:5064] 95 95 91 89 88 88 88 88 87 87 ...
 $ urban_rural           : Factor w/ 2 levels "Urban","Rural": 1 1 1 1 1 1 1 1 1 1 ...
 $ income_level          : Factor w/ 3 levels "Medium","Low",..: 1 1 2 1 1 2 1 2 2 2 ...
 $ marital_status        : Factor w/ 6 levels "Married","Widowed",..: 1 2 1 3 4 4 1 1 1 1 ...
 $ education             : Factor w/ 3 levels "Lower","Higher",..: 1 1 1 1 2 3 2 1 1 3 ...
 $ life_satisfaction     : num [1:5064] 7 4 5 8 6 6 6 5 6 8 ...
 $ freedom_of_choice     : num [1:5064] 8 7 5 10 6 5 6 5 5 10 ...
 $ financial_satisfaction: num [1:5064] 8 4 5 10 7 3 6 3 5 10 ...
 $ trust_people          : Factor w/ 2 levels "Not trusted",..: 1 1 1 1 1 1 2 1 1 1 ...
 $ importance_of_god     : num [1:5064] 10 10 10 7 3 1 8 1 10 1 ...
 $ emancipative_values   : num [1:5064] 0.229 0.693 0.338 0.49 0.526 ...
 $ secular_values        : num [1:5064] 0 0.153 0.495 0.503 0.433 ...
 $ avg_satisfaction      : num [1:5064] 7.5 4 5 9 6.5 4.5 6 4 5.5 9 ...
 $ age_group             : chr [1:5064] "61+" "61+" "61+" "61+" ...

Prep before analysis: convert to factors (shortcut ver.)

If we have a lot of columns to convert, that might be troublesome to type! This is where across() can come in handy. across(column selection, function) is to apply the same function or a set of functions to multiple columns in a single mutate () or summarize () function.

Let’s first define a character vector that contains the names of columns we plan to convert.

columns_to_convert <- c("country", "sex", "marital_status", "urban_rural", "income_level", "education", "trust_people")

We will use this vector with mutate() and across(). We tell tidyverse to convert all of the columns with the help of all_of()

wvs_cleaned <- wvs_cleaned |> 
    mutate(across(all_of(columns_to_convert), as_factor))

# check conversion result
str(wvs_cleaned)

across() is used for applying the same function to multiple columns in a single mutate() or summarise() operation.

Prep before analysis: convert to factors (shortcut ver.)

tibble [5,064 x 17] (S3: tbl_df/tbl/data.frame)
 $ respondent_id         : num [1:5064] 7.92e+08 7.92e+08 3.44e+08 3.44e+08 3.44e+08 ...
 $ country               : Factor w/ 4 levels "Turkey","Hong Kong SAR",..: 1 1 2 2 2 2 2 2 2 2 ...
 $ sex                   : Factor w/ 2 levels "Male","Female": 1 1 1 2 1 1 1 1 1 1 ...
 $ age                   : num [1:5064] 95 95 91 89 88 88 88 88 87 87 ...
 $ urban_rural           : Factor w/ 2 levels "Urban","Rural": 1 1 1 1 1 1 1 1 1 1 ...
 $ income_level          : Factor w/ 3 levels "Medium","Low",..: 1 1 2 1 1 2 1 2 2 2 ...
 $ marital_status        : Factor w/ 6 levels "Married","Widowed",..: 1 2 1 3 4 4 1 1 1 1 ...
 $ education             : Factor w/ 3 levels "Lower","Higher",..: 1 1 1 1 2 3 2 1 1 3 ...
 $ life_satisfaction     : num [1:5064] 7 4 5 8 6 6 6 5 6 8 ...
 $ freedom_of_choice     : num [1:5064] 8 7 5 10 6 5 6 5 5 10 ...
 $ financial_satisfaction: num [1:5064] 8 4 5 10 7 3 6 3 5 10 ...
 $ trust_people          : Factor w/ 2 levels "Not trusted",..: 1 1 1 1 1 1 2 1 1 1 ...
 $ importance_of_god     : num [1:5064] 10 10 10 7 3 1 8 1 10 1 ...
 $ emancipative_values   : num [1:5064] 0.229 0.693 0.338 0.49 0.526 ...
 $ secular_values        : num [1:5064] 0 0.153 0.495 0.503 0.433 ...
 $ avg_satisfaction      : num [1:5064] 7.5 4 5 9 6.5 4.5 6 4 5.5 9 ...
 $ age_group             : chr [1:5064] "61+" "61+" "61+" "61+" ...

Analysis 1 - summary stats of life_satisfaction for each country

Generate summary statistics such as count (n), mean, median, and standard deviation of life_satisfaction grouped by country.

We can achieve this with group_by() and summarise(). It will contain one column for each grouping variable and one column for each of the summary statistics that you have specified.

wvs_cleaned |>
    group_by(country) |>
    summarise(
        n = n(),
        mean_satisfaction = mean(life_satisfaction),
        median_satisfaction = median(life_satisfaction),
        sd_satisfaction = sd(life_satisfaction)
    ) |>
    arrange(desc(mean_satisfaction))

What if we want to save this into a CSV? What if we also want to group by country AND age_group?

Analysis 1 - summary stats of life_satisfaction for each country

# A tibble: 4 x 5
  country           n mean_satisfaction median_satisfaction sd_satisfaction
  <fct>         <int>             <dbl>               <dbl>           <dbl>
1 Indonesia      1297              7.53                   8            2.37
2 Malaysia       1292              7.02                   7            1.73
3 Hong Kong SAR  1265              6.55                   7            1.80
4 Turkey         1210              6.51                   7            1.84

Shortcut: counting rows with count()

Counting rows per group is so common that tidyverse has a shortcut for it:

# same as: group_by(country) |> summarise(n = n())
wvs_cleaned |> count(country)
# A tibble: 4 x 2
  country           n
  <fct>         <int>
1 Turkey         1210
2 Hong Kong SAR  1265
3 Indonesia      1297
4 Malaysia       1292

You can count by more than one column too, e.g. count(country, age_group).

Analysis 2 - How many has below and average life_satisfaction?

Create a new column called satisfaction_group that indicate whether each respondent has higher or lower than average life_satisfaction

mean_satisfaction <- mean(wvs_cleaned$life_satisfaction, na.rm = TRUE)

wvs_cleaned |>
    mutate(satisfaction_group = if_else(
        life_satisfaction > mean_satisfaction, # the condition to evaluate
        "higher", # if condition is fulfilled, do this
        "lower" # otherwise, do this
    )) 

Analysis 2 - How many has below and average life_satisfaction?

# A tibble: 5,064 x 18
   respondent_id country     sex     age urban_rural income_level marital_status
           <dbl> <fct>       <fct> <dbl> <fct>       <fct>        <fct>         
 1     792000461 Turkey      Male     95 Urban       Medium       Married       
 2     792001320 Turkey      Male     95 Urban       Medium       Widowed       
 3     344001151 Hong Kong ~ Male     91 Urban       Low          Married       
 4     344000263 Hong Kong ~ Fema~    89 Urban       Medium       Living togeth~
 5     344000655 Hong Kong ~ Male     88 Urban       Medium       Divorced      
 6     344000022 Hong Kong ~ Male     88 Urban       Low          Divorced      
 7     344001137 Hong Kong ~ Male     88 Urban       Medium       Married       
 8     344000104 Hong Kong ~ Male     88 Urban       Low          Married       
 9     344001233 Hong Kong ~ Male     87 Urban       Low          Married       
10     344000164 Hong Kong ~ Male     87 Urban       Low          Married       
# i 5,054 more rows
# i 11 more variables: education <fct>, life_satisfaction <dbl>,
#   freedom_of_choice <dbl>, financial_satisfaction <dbl>, trust_people <fct>,
#   importance_of_god <dbl>, emancipative_values <dbl>, secular_values <dbl>,
#   avg_satisfaction <dbl>, age_group <chr>, satisfaction_group <chr>

Analysis 3 - What’s the average satisfaction scores for each country and age group?

Show the average satisfaction scores by country and age group in wide data format

wvs_cleaned |>
    group_by(country, age_group) |>
    summarise(
        avg_satisfaction = mean(life_satisfaction, na.rm = TRUE),
    ) |>
    pivot_wider(
        names_from = age_group,
        values_from = avg_satisfaction
    ) 
# A tibble: 4 x 5
# Groups:   country [4]
  country       `18-28` `29-44` `45-60` `61+`
  <fct>           <dbl>   <dbl>   <dbl> <dbl>
1 Turkey           6.55    6.64    6.42  6   
2 Hong Kong SAR    6.41    6.30    6.59  6.91
3 Indonesia        7.50    7.69    7.41  7.15
4 Malaysia         7.09    6.90    7.14  6.94

Long vs Wide Data

Long data:

  • Each row is a unique observation –> for a single observational unit, there might be multiple rows.

  • There is a separate column indicating the variable or type of measurements.

  • This format is more “understandable” by R, more suitable for visualizations, especially those involving grouping, summarizing, or visualizing data over time or across different categories. (which we’ll explore more next week!)

Wide data:

  • Each row contains values from variables.

  • Each column is a value in a variable –> the more values you have, the “wider” is the data.

  • Quick comparisons of different variables for a single entity.

  • This format is more intuitive for humans!

Long vs Wide Data: Examples

Long data:

Observations (Long)
country age_group count
Indonesia 18-28 324
Indonesia 29-44 537
Indonesia 45-60 329
Indonesia 61+ 107
Malaysia 18-28 363
Malaysia 29-44 526
Malaysia 45-60 338
Malaysia 61+ 65

Wide data:

Observations (Wide)
country 18-28 29-44 45-60 61+
Indonesia 324 537 329 107
Malaysia 363 526 338 65

Bonus: Deleting columns from dataframe

Let’s say I have this column called wrong_column that I want to remove:

wvs_data <- wvs_data |> mutate(wrong_column = "random values")
wvs_data |> select(country, wrong_column) |> print(n = 3)
# A tibble: 5,064 x 2
  country       wrong_column 
  <chr>         <chr>        
1 Turkey        random values
2 Turkey        random values
3 Hong Kong SAR random values
# i 5,061 more rows

Remove the wrong column with subset -:

wvs_data <- wvs_data |> 
    select(-wrong_column)
# A tibble: 5,064 x 1
  country      
  <chr>        
1 Turkey       
2 Turkey       
3 Hong Kong SAR
# i 5,061 more rows

Recap

Clean (the six steps)

  1. Missing values: drop_na()
  2. Duplicates: distinct()
  3. Columns: select(), rename()
  4. Rows: filter(), arrange()
  5. New columns: mutate()
  6. Categories: case_when()

Analyse

  • Factors: as_factor() + across()
  • Summaries by group: group_by() + summarise(), or count()
  • Two-way labels: if_else()
  • Long to wide: pivot_wider()

Load with read_csv(), save checkpoints with write_csv().

End of Session 2!

Next session: Descriptive statistics and data visualization with ggplot2 package - we’ll create visualizations to explore patterns in life satisfaction, values, and demographics across countries!

Quiz Time! (compulsory)

Scan the QR Code below to assess your understanding of data wrangling in R using the tidyverse package. All questions are required and each is worth 1 mark.

Quiz QR Code: https://forms.cloud.microsoft/r/0Vhn9mfWur

Quiz QR Code: <https://forms.cloud.microsoft/r/0Vhn9mfWur>

To try at home: Exercise 1

Now that we have a new file, load this new wvs_cleaned_v1.csv into a new dataframe called wvs_cleaned. Filter to respondents from Indonesia who live in Urban areas. Show only the respondent_id, country, urban_rural, and age. Use glimpse() or print() to check the result! (you can chain these functions at the end)

Step 1: Load the new file

Show answer
library(tidyverse)
wvs_cleaned <- read_csv("data-output/wvs_cleaned_v1.csv")

Step 2: Do the filtering and selecting, and then show result

Show answer
library(tidyverse)
wvs_cleaned <- read_csv("data-output/wvs_cleaned_v1.csv")

wvs_cleaned |>
    filter(country == "Indonesia" & urban_rural == "Urban") |>
    select(respondent_id, country, urban_rural, age) |>
    glimpse()
Rows: 320
Columns: 4
$ respondent_id <dbl> 360000053, 360000530, 360000852, 360000535, 360001300, 3~
$ country       <chr> "Indonesia", "Indonesia", "Indonesia", "Indonesia", "Ind~
$ urban_rural   <chr> "Urban", "Urban", "Urban", "Urban", "Urban", "Urban", "U~
$ age           <dbl> 80, 71, 70, 70, 70, 68, 68, 68, 67, 66, 66, 65, 65, 65, ~

To try at home: Exercise 2

Generate a summary stats of age grouped by country and sex. The summary stats should include mean, median, max, min, std, and n (number of observations). It should look something like this:

Show answer
wvs_data |> 
    group_by(country, sex) |> 
    summarise(observation = n(), 
              mean_age = mean(age, na.rm = TRUE),
              median_age = median(age, na.rm = TRUE), 
              oldest = max(age, na.rm = TRUE),
              youngest = min(age, na.rm = TRUE),
              std_dev = sd(age, na.rm = TRUE))

To try at home: Exercise 2

# A tibble: 8 x 8
# Groups:   country [4]
  country       sex    observation mean_age median_age oldest youngest std_dev
  <chr>         <chr>        <int>    <dbl>      <dbl>  <dbl>    <dbl>   <dbl>
1 Hong Kong SAR Female         679     45.8         45     89       18    15.4
2 Hong Kong SAR Male           586     48.2         48     91       18    16.9
3 Indonesia     Female         719     37.2         35     74       18    12.6
4 Indonesia     Male           578     41.1         40     80       18    14.3
5 Malaysia      Female         633     38.0         35     80       18    12.7
6 Malaysia      Male           659     38.4         35     79       18    12.9
7 Turkey        Female         604     39.8         37     80       18    12.6
8 Turkey        Male           606     38.7         36     95       18    13.3

Appendix

Advanced tidyr and dplyr features you may need in the future.

Wide back to long with pivot_longer()

pivot_wider() has an opposite: pivot_longer(). Let’s take the wide table from the Long vs Wide Data examples and turn it back into long data (which ggplot prefers):

wide_data <- long_data |>
    pivot_wider(names_from = age_group, values_from = count)

wide_data |>
    pivot_longer(cols = -country, # every column except country
                 names_to = "age_group",
                 values_to = "count") |>
    print(n = 4)
# A tibble: 8 x 3
  country   age_group count
  <chr>     <chr>     <int>
1 Indonesia 18-28       324
2 Indonesia 29-44       537
3 Indonesia 45-60       329
4 Indonesia 61+         107
# i 4 more rows

Joining DataFrames by column

Let’s assume we have two DataFrames customers and orders

customers dataframe:

(Notice that the ID is 1, 2, and 3)

  id  name
1  1 Alice
2  2   Bob
3  3 Carol

orders dataframe

(Notice that the ID is 1, 2, and 4)

  id amount
1  1    100
2  2    200
3  4    150

left_join() to keep all rows from the left table i.e. customers

customers |> left_join(orders, by = "id")
  id  name amount
1  1 Alice    100
2  2   Bob    200
3  3 Carol     NA

right_join() to keep all rows from the right table i.e. orders

customers |> right_join(orders, by = "id")
  id  name amount
1  1 Alice    100
2  2   Bob    200
3  4  <NA>    150

inner_join() to keep only matching rows

customers |> inner_join(orders, by = "id")
  id  name amount
1  1 Alice    100
2  2   Bob    200

full_join() to keep all rows from both tables

customers |> full_join(orders, by = "id")
  id  name amount
1  1 Alice    100
2  2   Bob    200
3  3 Carol     NA
4  4  <NA>    150

bind_rows() to stack rows from two different dataframes

Let’s say we have the following dataframes

print(df1)
   name age
1 Alice  25
print(df2)
  name age
1  Bob  30

Stack them together:

df1 |> bind_rows(df2)
   name age
1 Alice  25
2   Bob  30

Splitting and combining cells

Let’s say we have the following dataframe

  first  last         full_address
1  John   Doe 123 Main St, NYC, NY
2  Jane Smith  456 Oak Ave, LA, CA

Combine first and last name columns into one

df <- df |> unite("full_name", "first", "last", sep = "_")
print(df)
   full_name         full_address
1   John_Doe 123 Main St, NYC, NY
2 Jane_Smith  456 Oak Ave, LA, CA

Split the full name column into multiple (by delimiter)

df <- df |> separate_wider_delim("full_name", delim = "_", names = c("first", "last"))
print(df)
# A tibble: 2 x 3
  first last  full_address        
  <chr> <chr> <chr>               
1 John  Doe   123 Main St, NYC, NY
2 Jane  Smith 456 Oak Ave, LA, CA 

Split one column into multiple rows (long format)

df |> separate_longer_delim(full_address, delim = ", ")
# A tibble: 6 x 3
  first last  full_address
  <chr> <chr> <chr>       
1 John  Doe   123 Main St 
2 John  Doe   NYC         
3 John  Doe   NY          
4 Jane  Smith 456 Oak Ave 
5 Jane  Smith LA          
6 Jane  Smith CA