dplyr and tidyr (part of the tidyverse package)Go to the folder where you put your project for this workshop
Find a file with .Rproj extension - this is the R project file that holds all the information about your project.
Double click on the file. Rstudio should launch with your project loaded!
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):
Environment panel is empty (click on broom icon to clean it up).Console and Plots too.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.
glimpse(), summary(), str()) before cleaning.drop_na() - remove rows with missing valuesselect() - pick columnsfilter() - pick rows based on criteriamutate() - create or edit columnsif_else() / case_when() - used inside mutate() to set values based on conditionsgroup_by() + summarize() - group data and summarize each groupJoining 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.
It’s not a must, but it’ll be make our job much easier! Key advantages:
Example:
We’re research assistants preparing WVS data from 4 countries (Hong Kong SAR, Indonesia, Malaysia, Turkey) for analysis.
avg_satisfaction: the average of life_satisfaction and financial_satisfactionA 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?
[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:
The number of observations after removing NAs:
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.
Check for duplicates with distinct()
(Our data has no duplicates, but this is still a good practice to do, especially if we were combining data from multipe sources)
Select only the relevant columns: respondent_id, demographic columns, and attitudinal columns.
We can achieve this with select()!
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,~
rename()Real survey exports often have long or messy column names. rename() uses the pattern new_name = old_name:
# 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.)
Filter for respondents aged 18 or older. Optionally, we can then arrange the dataset by age (oldest to youngest)
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>
%in%To keep rows that match any value in a list, use %in% inside filter(). It’s much easier to read than chaining |:
# 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.)
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.)
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
Create age groups for each generation: “18-28”, “29-44”, “45-60”, “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
We have done some cleaning! Let’s save this cleaned data into a separate CSV file called “wvs_cleaned_v1.csv”
Check the data output folder to make sure the CSV is created!
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
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.
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+" ...
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.
We will use this vector with mutate() and across(). We tell tidyverse to convert all of the columns with the help of all_of()
across() is used for applying the same function to multiple columns in a single mutate() or summarise() operation.
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+" ...
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.
What if we want to save this into a CSV? What if we also want to group by country AND age_group?
# 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
count()Counting rows per group is so common that tidyverse has a shortcut for it:
# 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).
Create a new column called satisfaction_group that indicate whether each respondent has higher or lower than 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>
Show the average satisfaction scores by country and age group in wide data format
# 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 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 data:
| 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:
| country | 18-28 | 29-44 | 45-60 | 61+ |
|---|---|---|---|---|
| Indonesia | 324 | 537 | 329 | 107 |
| Malaysia | 363 | 526 | 338 | 65 |
Let’s say I have this column called wrong_column that I want to remove:
-:# A tibble: 5,064 x 1
country
<chr>
1 Turkey
2 Turkey
3 Hong Kong SAR
# i 5,061 more rows
Clean (the six steps)
drop_na()distinct()select(), rename()filter(), arrange()mutate()case_when()Analyse
as_factor() + across()group_by() + summarise(), or count()if_else()pivot_wider()Load with read_csv(), save checkpoints with write_csv().
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!
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.
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
Step 2: Do the filtering and selecting, and then show result
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, ~
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:
# 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
Advanced tidyr and dplyr features you may need in the future.
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):
# 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
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
Let’s say we have the following dataframes
Stack them together:
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