diff --git a/.gitignore b/.gitignore index 7ad04cb..f2691ac 100644 --- a/.gitignore +++ b/.gitignore @@ -22,4 +22,7 @@ vendor/ # Ignore Notes and Old Files Notes/ -old/ \ No newline at end of file +old/ +**/*.quarto_ipynb + +.review/ \ No newline at end of file diff --git a/do_files/next_steps-data_discovery.do b/do_files/next_steps-data_discovery.do new file mode 100644 index 0000000..8d75f81 --- /dev/null +++ b/do_files/next_steps-data_discovery.do @@ -0,0 +1,44 @@ +* Load Packages +clear all +set more off + +* lookfor +use "safeguarded_eul/ns8_2015_derived.dta", clear +lookfor "ghq" + +* codebook +log using codebook.log, replace +codebook +log close + +* Create a Lookup Table Across All Datasets +* ssc install filelist +filelist, pattern("*.dta") +keep if !strmatch(dirname, "*UKDS*") +tempfile file_list +save `file_list' + +clear +tempfile all_vars +save `all_vars', emptyok + +use `file_list', clear +local n_files = _N +forvalues i = 1/`n_files' { + use `file_list' in `i', clear + local filename = filename[1] + local dirname = dirname[1] + use "`dirname'/`filename'", clear + describe *, replace + gen dir = "`dirname'" + gen file = "`filename'" + append using `all_vars' + save `all_vars', replace +} + +use `all_vars', clear +gen name_low = lower(name) +gen varlab_low = lower(varlab) +gen sweep = real(regexs(1)) if regexm(name_low, "^w([0-9])") // Extracts sweep from the variable name +list dir file sweep name varlab if strmatch(varlab_low, "*ghq*") +list dir file sweep name varlab if strmatch(varlab_low, "*ghq*") & strmatch(varlab_low, "*score*") diff --git a/do_files/next_steps-data_structures.do b/do_files/next_steps-data_structures.do new file mode 100644 index 0000000..0f01cfd --- /dev/null +++ b/do_files/next_steps-data_structures.do @@ -0,0 +1,18 @@ +clear all +set more off + +* Missing Values +capture program drop negative_to_na +program define negative_to_na + syntax varlist(numeric) + + foreach var of varlist `varlist' { + replace `var' = . if `var' < 0 + } +end + +use NSID W1alceverYP using "safeguarded_eul/wave_one_lsype_young_person_2020.dta", clear +numlabel, add // Adds numeric values to value labels +tabulate W1alceverYP, missing // Raw variable +negative_to_na W1alceverYP // Replaces negative values with missing (.) +tabulate W1alceverYP, missing // Cleaned variable diff --git a/do_files/next_steps-household_grid.do b/do_files/next_steps-household_grid.do new file mode 100644 index 0000000..8e9f425 --- /dev/null +++ b/do_files/next_steps-household_grid.do @@ -0,0 +1,64 @@ +clear all +set more off + +* Finding Mother +use NSID W1HhID W1Sex W1R_1 W1EmpStat using "household_grids/wave_one_lsype_household_grid_file_2020.dta", clear +numlabel, add // Adds numeric values to value labels +tabulate W1Sex +tabulate W1R_1 +keep if W1R_1 == 8 & W1Sex == 2 +bysort NSID: gen n = _N +keep if n == 1 +drop n +keep NSID W1HhID W1EmpStat +save "temp_mothers.dta", replace + +* Mother's Employment +tabulate W1EmpStat +gen mother_works = . +replace mother_works = 1 if inrange(W1EmpStat, 1, 2) +replace mother_works = 0 if inrange(W1EmpStat, 3, 9) +keep NSID mother_works +tabulate mother_works, missing + +* Main and Second Parent +use NSID W1HhID W1Sex W1R_1 W1mainres W1secores using "household_grids/wave_one_lsype_household_grid_file_2020.dta", clear +gen role = "Main parent" if W1HhID == W1mainres +replace role = "Second parent" if W1HhID == W1secores & role == "" +drop if role == "" +bysort role: tabulate W1R_1 W1Sex + +* Changes in Main Parent Across Sweeps +use NSID W1HhID W1mainres using "household_grids/wave_one_lsype_household_grid_file_2020.dta", clear +keep if W1HhID == W1mainres +rename W1HhID w1_main_hhid +keep NSID w1_main_hhid +save "temp_w1_main.dta", replace + +use NSID W2HhID W2mainres using "household_grids/wave_two_lsype_household_grid_file_2020.dta", clear +keep if W2HhID == W2mainres +rename W2HhID w2_main_hhid +keep NSID w2_main_hhid + +merge 1:1 NSID using "temp_w1_main.dta", keep(match) nogenerate +gen same_person = w1_main_hhid == w2_main_hhid +tabulate same_person + +* Relationships +use NSID W1HhID W1R_* using "household_grids/wave_one_lsype_household_grid_file_2020.dta", clear +list W1HhID W1R_1 W1R_2 W1R_3 if NSID == NSID[1] + +* Reshape for Partner +reshape long W1R_, i(NSID W1HhID) j(W1HhID_alter) +keep if inlist(W1R_, 1, 2) +keep NSID W1HhID W1HhID_alter +rename W1HhID_alter partner_hhid +list in 1/10 // One row per couple: each relationship is only recorded for the person with the higher person number +save "temp_couples.dta", replace + +* Add Row for Other Partner +rename (W1HhID partner_hhid) (partner_hhid W1HhID) // Swaps the person numbers of the two partners +append using "temp_couples.dta" +order NSID W1HhID partner_hhid +sort NSID W1HhID +list in 1/10 diff --git a/do_files/next_steps-merging_across_sweeps.do b/do_files/next_steps-merging_across_sweeps.do new file mode 100644 index 0000000..93a4ed5 --- /dev/null +++ b/do_files/next_steps-merging_across_sweeps.do @@ -0,0 +1,114 @@ +clear all +set more off + +* Merging Across Sweeps +use NSID W2ghq12scr using "safeguarded_eul/wave_two_lsype_young_person_2020.dta", clear +save "temp_w2.dta", replace + +use NSID W4ghq12scr using "safeguarded_eul/wave_four_lsype_young_person_2020.dta", clear +save "temp_w4.dta", replace + +use "temp_w2.dta", clear +merge 1:1 NSID using "temp_w4.dta" +list NSID W2ghq12scr W4ghq12scr _merge in 1/10 +// Use `drop if _merge == x` or run `merge ..., keep(x)` to keep a specific type of match/non-match. + +* Appending Sweeps +use "temp_w2.dta", clear +rename W2* * +gen sweep = 2 +save "temp_w2_long.dta", replace + +use "temp_w4.dta", clear +rename W4* * +gen sweep = 4 +save "temp_w4_long.dta", replace + +use "temp_w2_long.dta", clear +append using "temp_w4_long.dta" +sort NSID sweep +list NSID sweep ghq12scr in 1/10 + +* Add Missing Rows +fillin NSID sweep +list * in 1/10 + +* Programmatic Merging +* Lookup lists: the nth word of each list gives the sweep, file and variable to use +global sweeps 2 4 8 9 +global files safeguarded_eul/wave_two_lsype_young_person_2020.dta safeguarded_eul/wave_four_lsype_young_person_2020.dta safeguarded_eul/ns8_2015_derived.dta safeguarded_eul/ns9_2022_derived_variables.dta +global ghq_vars W2ghq12scr W4ghq12scr W8DGHQSC W9DGHQSC + +capture program drop load_ghq_wide +program define load_ghq_wide + args i + + local file : word `i' of ${files} + local ghq_var : word `i' of ${ghq_vars} + + use NSID `ghq_var' using "`file'", clear +end + +load_ghq_wide 3 +list * in 1/10 + +load_ghq_wide 1 + +tempfile next_merge +forvalues i = 2/4 { + preserve + load_ghq_wide `i' + save "`next_merge'", replace + restore + merge 1:1 NSID using "`next_merge'", nogenerate +} + +sort NSID +list * in 1/10 +save "temp_ghq_wide.dta", replace + +* Programmatic Appending +capture program drop load_ghq_long +program define load_ghq_long + args i + + load_ghq_wide `i' + local ghq_var : word `i' of ${ghq_vars} + local sweep : word `i' of ${sweeps} + rename `ghq_var' ghq12 + label values ghq12 . // Removes value labels, which differ between sweeps + gen sweep = `sweep' +end + +load_ghq_long 1 + +tempfile next_append +forvalues i = 2/4 { + preserve + load_ghq_long `i' + save "`next_append'", replace + restore + append using "`next_append'" +} + +sort NSID sweep +list * in 1/10 + +* Replace Negative Values with Missing +capture program drop negative_to_na +program define negative_to_na + syntax varlist(numeric) + + foreach var of varlist `varlist' { + replace `var' = . if `var' < 0 + } +end + +negative_to_na ghq12 +list * in 1/10 + +* Defining the Sample with the Longitudinal File +use NSID MAINBOOST W?OUTCOME using "safeguarded_eul/ns9_2022_longitudinal_file.dta", clear +tabulate MAINBOOST +merge 1:1 NSID using "temp_ghq_wide.dta", keep(master match) nogenerate +list * in 1/10 diff --git a/do_files/next_steps-merging_within_sweep.do b/do_files/next_steps-merging_within_sweep.do new file mode 100644 index 0000000..8f5f7d4 --- /dev/null +++ b/do_files/next_steps-merging_within_sweep.do @@ -0,0 +1,49 @@ +clear all +set more off + +* Sex and Attitude to School +use NSID W1sexYP W1yschat1 using "safeguarded_eul/wave_one_lsype_young_person_2020.dta", clear +rename (W1sexYP W1yschat1) (sex school_attitude) +save "df_yp.dta", replace + +* Tenure +use NSID W1hous12HH using "safeguarded_eul/wave_one_lsype_family_background_2020.dta", clear +rename W1hous12HH tenure +save "df_tenure.dta", replace + +* Family NS-SEC +use NSID W1nssecMP W1nssecSP using "safeguarded_eul/wave_one_lsype_family_background_2020.dta", clear +replace W1nssecMP = . if !inrange(W1nssecMP, 1, 8) // Values outside 1-8 denote various forms of missingness +replace W1nssecSP = . if !inrange(W1nssecSP, 1, 8) +egen family_nssec = rowmin(W1nssecMP W1nssecSP) // Lowest value of the two variables in each row +keep NSID family_nssec +save "df_nssec.dta", replace + +* Mother's NS-SEC +use NSID W1mainres W1secores W1nssecMP W1nssecSP using "safeguarded_eul/wave_one_lsype_family_background_2020.dta", clear +rename (W1mainres W1secores) (W1HhIDMP W1HhIDSP) +reshape long W1HhID W1nssec, i(NSID) j(parent) string // One row per parent +save "temp_parent.dta", replace + +use NSID W1HhID W1Sex W1R_1 using "household_grids/wave_one_lsype_household_grid_file_2020.dta", clear +joinby NSID W1HhID using "temp_parent.dta" // Keeps matched rows only +keep if W1R_1 == 8 & W1Sex == 2 +bysort NSID: gen n = _N +keep if n == 1 +gen mother_nssec = W1nssec if inrange(W1nssec, 1, 8) +keep NSID mother_nssec +save "df_mother_nssec.dta", replace + +* Number of Siblings +use NSID W1HhID W1R_1 using "household_grids/wave_one_lsype_household_grid_file_2020.dta", clear +gen sibling = inrange(W1R_1, 13, 17) +collapse (sum) n_siblings = sibling, by(NSID) +save "df_siblings.dta", replace + +* Merge All +use "df_yp.dta", clear +merge 1:1 NSID using "df_tenure.dta", keep(master match) nogenerate +merge 1:1 NSID using "df_nssec.dta", keep(master match) nogenerate +merge 1:1 NSID using "df_mother_nssec.dta", keep(master match) nogenerate +merge 1:1 NSID using "df_siblings.dta", keep(master match) nogenerate +list in 1/10 diff --git a/do_files/next_steps-reshape_long_wide.do b/do_files/next_steps-reshape_long_wide.do new file mode 100644 index 0000000..d0b9d27 --- /dev/null +++ b/do_files/next_steps-reshape_long_wide.do @@ -0,0 +1,43 @@ +clear all +set more off + +* Load and Merge +use NSID W8HEIGHT W8WEIGHT using "safeguarded_eul/ns8_2015_main_interview.dta", clear +save "temp_w8.dta", replace + +use NSID W9HEIGHT W9WEIGHT using "safeguarded_eul/ns9_2022_main_interview.dta", clear +merge 1:1 NSID using "temp_w8.dta", nogenerate +order NSID W8HEIGHT W8WEIGHT W9HEIGHT W9WEIGHT +sort NSID +list in 1/10 + +* Reshape Raw Wide to Long +rename (W#HEIGHT W#WEIGHT) (HEIGHT# WEIGHT#) // reshape requires the sweep number to be at the end of the name +reshape long HEIGHT WEIGHT, i(NSID) j(sweep) +list in 1/10 + +* Reshape Raw Long to Wide +reshape wide HEIGHT WEIGHT, i(NSID) j(sweep) +rename (HEIGHT# WEIGHT#) (W#HEIGHT W#WEIGHT) +list in 1/10 + +* Cleaned Data +global ages 14 15 16 17 18 19 20 25 32 + +rename (W#HEIGHT W#WEIGHT) (HEIGHT# WEIGHT#) +reshape long HEIGHT WEIGHT, i(NSID) j(sweep) +gen age = real(word("${ages}", sweep)) +gen height = HEIGHT if HEIGHT > 0 +gen weight = WEIGHT if WEIGHT > 0 +keep NSID age height weight +list in 1/10 + +* Reshape Clean Long to Wide +reshape wide height weight, i(NSID) j(age) +rename (height# weight#) (height_# weight_#) +list in 1/10 + +* Reshape Clean Wide to Long +reshape long height_ weight_, i(NSID) j(age) +rename (height_ weight_) (height weight) +list in 1/10 diff --git a/docs/images/next_steps-data_discovery.png b/docs/images/next_steps-data_discovery.png new file mode 100644 index 0000000..176ce26 Binary files /dev/null and b/docs/images/next_steps-data_discovery.png differ diff --git a/docs/next_steps-data_discovery.md b/docs/next_steps-data_discovery.md new file mode 100644 index 0000000..882ea88 --- /dev/null +++ b/docs/next_steps-data_discovery.md @@ -0,0 +1,223 @@ +--- +layout: default +title: Data Discovery +nav_order: 1 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + + +- [Download the R script for this + page](../purl/next_steps-data_discovery.R) +- [Download the equivalent Stata script for this + page](../do_files/next_steps-data_discovery.do) + +# Introduction + +In this section, we show a few `R` functions for exploring Next Steps +data; there’s a lot of data in Next Steps, so finding a specific +variable can be challenging. Variable names do not always follow a +consistent convention across the whole study: Sweeps 1-7 were managed by +the Department for Education and Sweeps 8-9 by CLS, and the same concept +is often named differently in the two eras. (The variable for the cohort +member’s GHQ-12 score is `W2ghq12scr` in Sweep 2 but `W8DGHQSC` in Sweep +8, for example.) In what follows, we will use the `R` functions to find +variables for cohort members’ GHQ-12 (12-item General Health +Questionnaire), which has been collected in several of the sweeps. + +The packages we will use are: + +``` r +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For searching imported datasets +library(codebookr) # For creating .docx codebooks +``` + +As a reminder, the Next Steps data files downloaded from the UK Data +Service are stored across three subfolders: `safeguarded_eul`, +`household_grids` and `activity_histories`. The code below assumes that +your working directory is the folder that contains these three +subfolders (see the [*Next Steps* landing +page](https://cls-data.github.io/docs/next_steps.html)). + +# `labelled::lookfor()` + +The `labelled` package contains functionality for attaching and +examining metadata in dataframes (for instance, adding labels to +variables \[columns\]). Beyond this, it also contains the `lookfor()` +function, which replicates similar functionality in `Stata`. `lookfor()` +allows one to search for variables in a dataframe by keyword (regular +expression); the function searches variable names as well as associated +metadata (value and variable labels). It returns an object containing +matching variables, their labels, and their types, etc.. Below, we read +in the Next Steps Sweep 8 (age 25) dataset which contains derived +variables (`safeguarded_eul/ns8_2015_derived.dta`) and use `lookfor()` +to search for variables related to the `"GHQ"`. + +``` r +ns_w8 <- read_dta("safeguarded_eul/ns8_2015_derived.dta") + +lookfor(ns_w8, "ghq") +``` + + pos variable label col_type missing values + 53 W8DGHQSC DV: General Health Que~ dbl+lbl 0 [-9] Refused + [-8] Insufficient info~ + [-1] Not applicable + +Users may consider it easier to create a tibble of the `lookfor()` +output, which can be searched and filtered using `dplyr` functions. +Below, we create a `tibble` (a type of `data.frame` with good printing +defaults) of the `lookfor()` output and use `filter()` to find variables +with `"ghq"` in their labels. Note, we convert both the variable names +and labels to lower case to make the search case insensitive. + +``` r +ns_w8_lookfor <- lookfor(ns_w8) %>% + as_tibble() %>% + mutate(variable_low = str_to_lower(variable), + label_low = str_to_lower(label)) + +ns_w8_lookfor %>% + filter(str_detect(label_low, "ghq")) +``` + + # A tibble: 1 × 9 + pos variable label col_type missing levels value_labels variable_low + + 1 53 W8DGHQSC DV: General … dbl+lbl 0 w8dghqsc + # ℹ 1 more variable: label_low + +The output shows that GHQ information in the +`safeguarded_eul/ns8_2015_derived.dta` dataset is stored in the variable +`W8DGHQSC`. + +# `codebookr::codebook()` + +The Next Steps datasets that are downloadable from the UK Data Service +come bundled with data dictionaries within the `mrdoc` subfolder. +However, these are limited in some ways. The `codebookr` package enables +the creation of data dictionaries that are more customisable, and in our +opinion, easy to read. Below we create a codebook for the Next Steps +Sweep 8 derived variable dataset. These codebooks are intended to be +saved and viewed in Microsoft Word. + +``` r +cdb <- codebook(ns_w8) +print(cdb, "ns_w8_codebook.docx") # Saves as .docx (Word) file +``` + +A screenshot of the codebook is shown below. + +![Codebook created by +codebookr::codebook()](../images/next_steps-data_discovery.png) + +# Create a Lookup Table Across All Datasets + +Creating the `lookfor()` and `codebook()` one dataset at a time does not +allow one to get a quick overview of the variables available in Next +Steps, including the sweeps repeatedly measured characteristics are +available in. Below we create a `tibble`, `df_lookfor`, that contains +`lookfor()` results for all the `.dta` files in the three Next Steps +subfolders. + +To do this, we create a function, `create_lookfor()`, that takes a file +path to a `.dta` file, reads in the first row of the dataset (faster +than reading the full dataset), and applies `lookfor()` to it. We call +this function with a `mutate()` function call to create a set of lookups +for every `.dta` file we can find in the three subfolders (the argument +`full.names = TRUE` means `list.files()` returns the subfolder as well +as the file name; e.g., `safeguarded_eul/ns8_2015_derived.dta`). `map()` +loops over every value in the `file_path` column, creating a +corresponding lookup table for that file, stored as a +[`list-column`](https://r4ds.hadley.nz/rectangling.html#list-columns). +`unnest()` expands the results out, so rather than have one row per +`file_path`, we have one row per variable. `separate()` splits the file +path into two new columns, containing the subfolder and the file name. + +Unlike the other CLS cohorts, the Next Steps files are not organised +into a separate folder for each sweep. However, as [variable names begin +with a prefix indicating the +sweep](https://cls-data.github.io/docs/next_steps-data_structures.html) +(`W1`, `W2`, …, `W9`), we can instead extract the sweep from the +variable name. We do this in the second `mutate()` step below using the +`str_extract()` function, which takes a regular expression: `"^w(\\d)"` +matches a `w` at the start of the variable name followed by a single +digit (`\\d`), and `group = 1` returns the part of the match within the +parentheses (i.e., the digit). Variables that do not have a sweep prefix +(for example, `NSID`) are given the value `NA`. + +``` r +create_lookfor <- function(file_path){ + read_dta(file_path, n_max = 1) %>% + lookfor() %>% + as_tibble() +} + +folders <- c("activity_histories", "household_grids", "safeguarded_eul") + +df_lookfor <- tibble(file_path = list.files(folders, pattern = "\\.dta$", full.names = TRUE)) %>% + mutate(lookfor = map(file_path, create_lookfor)) %>% + unnest(lookfor) %>% + mutate(variable_low = str_to_lower(variable), + label_low = str_to_lower(label), + sweep = str_extract(variable_low, "^w(\\d)", group = 1) %>% + as.integer()) %>% + separate(file_path, + into = c("folder", "file"), + sep = "/", + remove = FALSE) %>% + relocate(sweep, .after = file) %>% + relocate(file_path, pos, .after = last_col()) +``` + +We can use the resulting object to search for variables with `"ghq"` in +their labels. + +``` r +df_lookfor %>% + filter(str_detect(label_low, "ghq")) %>% + select(file, sweep, variable, label) +``` + + # A tibble: 30 × 4 + file sweep variable label + + 1 ns8_2015_derived.dta 8 W8DGHQSC DV: General Health Questionnair… + 2 ns8_2015_self_completion.dta 8 W8GHQ12_1 GHQ12: Concentrate on what doing + 3 ns8_2015_self_completion.dta 8 W8GHQ12_2 GHQ12: Lost sleep over worry + 4 ns8_2015_self_completion.dta 8 W8GHQ12_3 GHQ12: Playing a useful part in… + 5 ns8_2015_self_completion.dta 8 W8GHQ12_4 GHQ12: Capable of making decisi… + 6 ns8_2015_self_completion.dta 8 W8GHQ12_5 GHQ12: Constantly under strain + 7 ns8_2015_self_completion.dta 8 W8GHQ12_6 GHQ12: Can’t overcome difficult… + 8 ns8_2015_self_completion.dta 8 W8GHQ12_7 GHQ12: Enjoy day to day activit… + 9 ns8_2015_self_completion.dta 8 W8GHQ12_8 GHQ12: Face up to problems + 10 ns8_2015_self_completion.dta 8 W8GHQ12_9 GHQ12: Unhappy or depressed + # ℹ 20 more rows + +The sweep prefix also makes it straightforward to see how the name of a +variable changes over time. For instance, below we search for GHQ-12 +*scores* (as opposed to the individual GHQ-12 items) by adding a second +condition to `filter()`. The names follow one convention in the Sweep 2 +and 4 files, and another in the Sweep 8 and 9 files. + +``` r +df_lookfor %>% + filter(str_detect(label_low, "ghq"), + str_detect(label_low, "score")) %>% + select(file, sweep, variable, label) +``` + + # A tibble: 6 × 4 + file sweep variable label + + 1 ns8_2015_derived.dta 8 W8DGHQSC DV: General Health Que… + 2 ns9_2022_derived_variables.dta 9 W9DGHQSC DV: General Health Que… + 3 wave_four_lsype_young_person_2020.dta 4 W4ghq12scr DV: Young person GHQ12… + 4 wave_four_lsype_young_person_2020.dta 4 W4ghqg DV: Young person GHQ S… + 5 wave_two_lsype_young_person_2020.dta 2 W2ghq12scr DV: Young person GHQ12… + 6 wave_two_lsype_young_person_2020.dta 2 W2ghqg DV: Young person GHQ S… diff --git a/docs/next_steps-data_structures.md b/docs/next_steps-data_structures.md new file mode 100644 index 0000000..4297edf --- /dev/null +++ b/docs/next_steps-data_structures.md @@ -0,0 +1,454 @@ +--- +layout: default +title: Data Structures +nav_order: 2 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + + +- [Download the R script for this + page](../purl/next_steps-data_structures.R) +- [Download the equivalent Stata script for this + page](../do_files/next_steps-data_structures.do) + +# Introduction + +Once you have downloaded the Next Steps data from the UK Data Service, +you will find over fifty data files, split across three subfolders. The +files differ in the sweep(s) they relate to, the part of the interview +they cover, and - in some cases - the observational unit they describe. +Most files contain one row per cohort member, but some contain one row +per household member, one row per activity, and so on. The aim of this +page is to give you an overview of the files and of the features of the +study design that determine how they should be used. + +Compared with the [Millennium Cohort +Study](https://cls-data.github.io/docs/mcs-data_structures.html), the +data structures in Next Steps are simple. There is one cohort member per +family, so a single variable, `NSID`, identifies both the cohort member +and their family. `NSID` appears, with the same name, in every file. +Further, where information was collected from or about a cohort member’s +parents, it is stored in the cohort member’s row (in separate variables +for each parent) rather than in separate rows. As a result, most files +can be merged one-to-one using `NSID` alone. + +# Subfolders + +The data files are provided in three subfolders. Unlike the other CLS +cohorts, the subfolders do not correspond to sweeps - each contains +files from several sweeps. + +- `safeguarded_eul` + - Contains the main survey files for each sweep, including the cohort + member and parent interviews and derived variables. Almost all of + the files with one row per cohort member are found here. +- `household_grids` + - Contains files with one row for each person the cohort member lives + with (see [below](#household-grid-files)). +- `activity_histories` + - Contains files with one row for each spell of education, employment + or other activity reported by the cohort member. + +The code on this website assumes that your working directory is the +folder that contains these three subfolders, so files are referred to by +both their subfolder and file name (e.g., +`safeguarded_eul/ns8_2015_derived.dta`). + +# Naming Conventions + +Next Steps was managed by the Department for Education (DfE) for Sweeps +1-7, when it was known as the Longitudinal Study of Young People in +England (LSYPE), and by CLS from Sweep 8 onwards. The file names reflect +this history. Files from Sweeps 1-7 begin `wave_[one-seven]` (the sweep +is written as a word), while files from Sweeps 8 and 9 begin `ns8_2015` +and `ns9_2022`, respectively. A small number of files combine +information from several sweeps. The star (`*`) in the file names below +is used as a wildcard. + +| File(s) | Subfolder | Sweeps | One row per… | Identifier(s) | +|----|----|----|----|----| +| `wave_*_lsype_young_person_2020.dta` | `safeguarded_eul` | 1-7 | Cohort member | `NSID` | +| `wave_*_lsype_family_background_2020.dta` | `safeguarded_eul` | 1-5 | Cohort member | `NSID` | +| `wave_*_lsype_parental_attitudes_*.dta` | `safeguarded_eul` | 1-4 | Cohort member | `NSID` | +| `wave_*_lsype_household_grid_file_2020.dta` | `household_grids` | 1-7 | Household member | `NSID` and a person number | +| `wave_*_activity_history_file_2020.dta` | `activity_histories` | 4-7 | Activity | `NSID` and an activity number | +| `ns8_2015_main_interview.dta`, `ns8_2015_self_completion.dta`, `ns8_2015_derived.dta` | `safeguarded_eul` | 8 | Cohort member | `NSID` | +| `ns9_2022_main_interview.dta`, `ns9_2022_derived_variables.dta` | `safeguarded_eul` | 9 | Cohort member | `NSID` | +| Other `ns8_2015_*.dta` and `ns9_2022_*.dta` files | All three | 8-9 | Partnership, child, household member, etc. | `NSID` and a second identifier | +| `ns9_2022_longitudinal_file.dta` | `safeguarded_eul` | All | Cohort member | `NSID` | + +We describe each of these in more detail below. + +# Variable Names + +Variable names begin with a prefix that identifies the sweep: `W1` for +Sweep 1, `W2` for Sweep 2, and so on (“W” stands for wave, the term used +in DfE documentation). In Sweeps 1-7, the prefix is followed by the name +of the question in the questionnaire and then, usually, a suffix that +identifies who the question was asked of or relates to. The most common +suffixes are: + +- `YP` - the young person (i.e., the cohort member) +- `MP` - the main parent +- `SP` - the second parent +- `HH` - the household + +For instance, `W1hiqualgMP` and `W1hiqualgSP` contain the highest +qualification of the main parent and second parent, respectively, at +Sweep 1. Questions where more than one answer could be given are stored +as a set of binary variables, one for each answer, with a further +two-character suffix (`0a`, `0b`, `0c`, …) at the end of the variable +name. + +Variable labels in Sweeps 1-7 also begin with a prefix identifying the +source of the variable: `YP:`, `MP:`, `SP:`, `HH:` (household section), +`HR:` (history section), `DV:` (derived variable), and `Admin:` (survey +administration). Derived variables do not always carry a suffix. + +In Sweeps 8 and 9, variable names are in upper case and do not have a +suffix, as only the cohort member was interviewed (e.g., `W8HEIGHT`). +Derived variables begin `W8D` or `W9D` (e.g., `W8DGHQSC`). + +There are two things to be careful of. First, variables measuring the +same thing are usually named consistently between sweeps within the DfE +era (Sweeps 1-7) and within the CLS era (Sweeps 8-9), but not across +eras. Second, the use of upper and lower case is not consistent, even +for variables that are otherwise named identically (e.g., `W1alceverYP` +and `W4AlcEverYP`; `W1wrk2MP` and `W1Wrk2SP`). In a few places, the +sweep prefix itself is in lower case (e.g., `w3HhID` in the Sweep 3 +household grid). See [*Data +Discovery*](https://cls-data.github.io/docs/next_steps-data_discovery.html) +for ways of finding the variables you need. + +# Young Person, Family Background and Parental Attitudes Files + +In Sweeps 1-7, the main survey data are split across up to three files +(within the `safeguarded_eul` subfolder), each with one row per cohort +member: + +- `wave_[one-seven]_lsype_young_person_2020.dta` + - Contains the cohort member’s interview, as well as answers given by + the main parent about the cohort member (e.g., on special + educational needs). +- `wave_[one-five]_lsype_family_background_2020.dta` + - Contains information about the household (e.g., housing tenure) and + about the cohort member’s parents (e.g., their qualifications, + employment and health). Parents were not interviewed after Sweep 4. + At Sweep 5, limited information on parents was provided by the + cohort member. +- `wave_[one-four]_lsype_parental_attitudes_*.dta` + - Contains the main parent’s attitudes to the cohort member’s + schooling and their aspirations for the cohort member. + +As each of these files has one row per cohort member, they can be merged +using `NSID` alone (see [*Combining Data Within A +Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html)). +Below is a schematic of the family background file, which shows how +information on the main and second parent is stored in separate columns, +rather than separate rows. + +| `NSID` | `W1hous12HH` | `W1hiqualgMP` | `W1hiqualgSP` | … | +|--------|---------------|-----------------|----------------------|-----| +| NS0001 | 1 (Household) | 1 (Main parent) | 4 (Second parent) | … | +| NS0002 | 4 (Household) | 3 (Main parent) | -98 (SP not present) | … | +| NS0003 | 2 (Household) | 7 (Main parent) | 2 (Second parent) | … | +| … | … | … | … | … | + +A further file, +`lsype_history_file_wave_one_and_wave_two_june_2008.dta`, contains +information on the cohort member’s early life (e.g., birth weight) and +their family history, as reported by a parent at Sweep 1 or 2. +`wave_four_lsype_history_2020.dta` contains similar information +collected at Sweep 4. + +# Main and Second Parents + +In Sweeps 1-4, up to two of the cohort member’s parents (or guardians) +were interviewed. These are referred to as the “main parent” and the +“second parent”. It is important to understand that these are *roles in +the interview*, not fixed individuals: + +- In Sweeps 1-3, the main parent was defined as the parent most involved + in the young person’s education. At Sweep 4, the main parent could be + either parent - for the original sample, interviewers selected the + parent they felt was more likely to take part. For the Sweep 4 boost + sample, the main parent was the natural mother if available, then the + natural father, then the parent most involved in the young person’s + education. +- At Sweep 1, the second parent was defined as another adult with a + parental relationship to the young person (a natural, step, adoptive + or foster parent). From Sweep 2, the second parent was defined as the + partner or spouse of the main parent. +- There was no separate second parent interview at Sweep 3. Instead, the + main parent answered questions on behalf of both parents. At Sweep 4, + questions about the second parent were answered by the second parent + if they were present and by the main parent otherwise. +- Parents were not interviewed where the young person had moved out of + the parental home. + +The main and second parent roles were not carried forward from one sweep +to the next. A mother may have been the main parent at Sweep 1 and the +second parent at Sweep 2, for example, and the person occupying a role +may also have changed because someone joined or left the household. A +variable such as `W2hiqualgMP` does not, therefore, necessarily refer to +the same person as `W1hiqualgMP`. + +There are two ways of working out who the main and second parent are: + +1. For many characteristics, the family background files contain + derived variables that refer to the cohort member’s mother and + father, rather than the main and second parent (e.g., `W1hiqualgmum` + and `W1hiqualgdad`). The files also contain the sex of the main and + second parent (e.g., `W1sexMP` and `W1sexSP`). +2. The family background and household grid files contain variables + that give the position of the main and second parent in the + household grid (e.g., `W1mainres` and `W1secores` at Sweep 1). The + household grid records each household member’s sex and their + relationship to the cohort member. As a household member is intended + to keep the same position in the household grid in each sweep, these + variables can also be compared across sweeps to see whether the + person in a given role has changed. + +We show how to use the second of these in [*Working with the Household +Grid*](https://cls-data.github.io/docs/next_steps-household_grid.html). + +Where a variable relates to a parent who was not identified or not +interviewed, specific missing value codes are used: `-98` indicates that +there is no such parent in the household (e.g., there is no second +parent in a lone parent family) and `-99` that the parent was not +interviewed. + +# Household Grid Files + +The `wave_[one-seven]_lsype_household_grid_file_2020.dta` files, which +are stored in the `household_grids` subfolder, contain rosters of +household members. There is one row for each individual in the +household, including the cohort member. Individuals are identified by +the combination of `NSID` and a person number, which is named `W1HhID`, +`W2HhID`, `w3HhID`, and `W4hhid` in Sweeps 1-4 and `HHID` in Sweeps 5-7. +The cohort member is always person number 1. + +| `NSID` | `W1HhID` | `W1Sex` | `W1R_1` | … | +|--------|----------|------------|-----------------------------|-----| +| NS0001 | 1 | 2 (Female) | -91 (Not applicable) | … | +| NS0001 | 2 | 2 (Female) | 8 (Natural parent) | … | +| NS0001 | 3 | 1 (Male) | 8 (Natural parent) | … | +| NS0001 | 4 | 1 (Male) | 13 (Natural brother/sister) | … | +| NS0002 | 1 | 1 (Male) | -91 (Not applicable) | … | +| NS0002 | 2 | 2 (Female) | 8 (Natural parent) | … | +| … | … | … | … | … | + +In Sweeps 1-4, the household grid was typically completed by a parent +and records the relationships between household members in a series of +variables (`W1R_1`, `W1R_2`, and so on, at Sweep 1). The number at the +end of the variable name is the person number of the other household +member. Each relationship is only recorded once, in the row of the +person with the higher person number (so, at Sweep 1, `W1R_2` is only +filled in for household members with a person number of 3 or more), and +the variables are otherwise coded as not applicable (`-91`). As the +cohort member is person number 1, `W1R_1` records every other household +member’s relationship to the cohort member. The person numbers of the +main parent and second parent are also recorded (`W1mainres` and +`W1secores` at Sweep 1). In Sweeps 5-7, the household grid was completed +by the cohort member and contains much less information: a single, less +detailed variable (e.g., `W5RELATION`) records each person’s +relationship to the cohort member (at Sweep 7, this is only filled in +for people who are new to the household at that sweep). + +The household grid files are described further in [*Working with the +Household +Grid*](https://cls-data.github.io/docs/next_steps-household_grid.html). + +# Sweep 8 and 9 Files + +From Sweep 8, only the cohort member was interviewed. For each sweep, +the bulk of the data is stored in “flat” files with one row per cohort +member: + +- `ns8_2015_main_interview.dta` and `ns9_2022_main_interview.dta` + - Contain the main interview. +- `ns8_2015_self_completion.dta` + - Contains the Sweep 8 self-completion questionnaire. (At Sweep 9, + self-completion questions are included in the main interview file.) +- `ns8_2015_derived.dta` and `ns9_2022_derived_variables.dta` + - Contain derived variables (e.g., body mass index). + +The remaining files are “hierarchical”. These store the answers to sets +of questions that were repeated as many times as necessary - for +instance, once for each of the cohort member’s children. Each can have +multiple rows per cohort member and include a second identifier that +distinguishes the rows belonging to the same cohort member. Cohort +members for whom the questions were not relevant (e.g., those without +children) do not appear in the file at all. + +| File | One row per… | Identifiers | +|----|----|----| +| `ns8_2015_partnerships.dta` | Relationship | `NSID`, `W8RELID` | +| `ns8_2015_children.dta` | Child of the cohort member | `NSID`, `W8CHID` | +| `ns8_2015_household_members.dta` | Other household member | `NSID`, `W8HHMID` | +| `ns8_2015_activity_history.dta` | Activity | `NSID`, `W8HISTID` | +| `ns8_2015_benefits.dta` | Benefit received | `NSID`, `W8BENID` | +| `ns9_2022_partnerships.dta` | Relationship | `NSID`, `W9RELID` | +| `ns9_2022_person_grid.dta` | Partner, child or other household member | `NSID`, `GRIDID` | +| `ns9_2022_non_resident_children.dta` | Non-resident child | `NSID`, `GRIDID` | +| `ns9_2022_pregnancy_history.dta` | Child within a pregnancy | `NSID`, `W9PREGID`, `W9CHILDNO` | +| `ns9_2022_activity_history.dta` | Activity | `NSID`, `W9ACTID` | +| `ns9_2022_benefits.dta` | Benefit received | `NSID`, `W9BENID` | + +Most of these files are stored in the `safeguarded_eul` subfolder +alongside the flat files. The exceptions are +`ns8_2015_household_members.dta` and `ns9_2022_person_grid.dta`, which +are in the `household_grids` subfolder, and the two activity history +files, which are in the `activity_histories` subfolder. + +To use these files alongside the flat files, they generally need to be +collapsed or reshaped so that they have one row per cohort member. We +show an example of this in [*Combining Data Within A +Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html). + +# Cross-Sweep Files + +A small number of files bring together information from several sweeps. +These are all stored in the `safeguarded_eul` subfolder. + +- `ns9_2022_longitudinal_file.dta` + - Contains one row for every cohort member, regardless of the sweeps + they took part in. It includes the sample design variables + (`SAMPPSU` and `SAMPSTRATUM`), survey weights, the fieldwork outcome + at each sweep (`W[1-9]OUTCOME`), and an indicator of whether the + cohort member is part of the original or boost sample (`MAINBOOST`). + This is a useful starting point for defining your sample. +- `lsype_main_activity_w4-7_nov2011_suppressed.dta` + - Contains one row per cohort member, with a variable for the cohort + member’s main activity (e.g., education or employment) in each month + between September 2006 and May 2010. +- `next_steps_activities_longitudinal.dta` + - Contains one row per activity, summarising the activity histories + collected in Sweeps 4-8. + +# The Sweep 4 Boost Sample + +The original Next Steps sample was drawn in 2004, when cohort members +were in Year 9 at school. At Sweep 4, the study was enlarged with an +ethnic minority boost sample of 352 young people from Black African and +Black Caribbean backgrounds, selected from schools that did not take +part in the original sampling. + +This has important consequences for how the data are used: + +- Boost sample members have no data for Sweeps 1-3. This is not a result + of non-response. Some background information that was collected from + the original sample in Sweeps 1-3 was instead collected from the boost + sample at Sweep 4, so the Sweep 4 files contain variables that were + only asked of boost sample members. +- Analyses that use data from Sweeps 1-3 are necessarily restricted to + the original sample, and different survey weights are provided for + analyses that include and exclude the boost sample (e.g., + `W4WEIGHT_MAIN_BOOST` and `W4WEIGHT_MAIN` in + `ns9_2022_longitudinal_file.dta`). + +Boost sample members can be identified in two ways: + +- `W4Boost` in `wave_four_lsype_young_person_2020.dta` (`1 [Yes]` or + `2 [No]`). This variable is also available in the other Sweep 4 files. +- `MAINBOOST` in `ns9_2022_longitudinal_file.dta` (`1 [Main]` or + `2 [Boost]`). As this file contains every cohort member, `MAINBOOST` + is available for individuals who did not take part in Sweep 4. + +# Missing Values + +Negative values are used to indicate different forms of missing data. +The values used differ between the DfE and CLS eras. The most common are +shown below, though individual variables may use other codes. It is +always worth checking the value labels of a variable before using it. + +| Sweeps 1-7 | | Sweeps 8-9 | | +|----|----|----|----| +| `-1` | Don’t know | `-1` | Not applicable | +| `-91` | Not applicable | `-3` | Not asked | +| `-92` | Refused | `-8` | Don’t know or insufficient information | +| `-94` | Insufficient information | `-9` | Refused | +| `-96` | Unable to complete self-completion section | | | +| `-97` | Refused self-completion section | | | +| `-98` | Parent not present in household | | | +| `-99` | Respondent not interviewed | | | +| `-996` | No parent in household | | | +| `-997` | Script error | | | +| `-998` | Interviewer missed question | | | +| `-999` | Missing household data | | | + +Note in particular that `-1` means “Don’t know” in Sweeps 1-7 but “Not +applicable” in Sweeps 8 and 9. + +`R` does not know that these values denote missing data. Unless they are +dealt with, negative values are treated as valid values: a mean or a +regression model would include values such as `-92`, for instance, and +each type of missingness would appear as a category of its own in a +tabulation. Negative values therefore usually need to be converted to +`R`’s missing value, `NA`, before a variable is used in an analysis. +Below, we show one way of doing this, using the following packages: + +``` r +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For handling missing values +``` + +We create a short function, `negative_to_na()`, which uses two functions +from the `labelled` package: `na_range()` declares that all values +between negative infinity (`-Inf`) and `-1` denote missing data, and +`user_na_to_na()` converts the values that have been declared as missing +to `NA`. + +``` r +negative_to_na <- function(x){ + na_range(x) <- c(-Inf, -1) + user_na_to_na(x) +} +``` + +To show the function in action, we load the variable `W1alceverYP` +(whether the cohort member has ever had a proper alcoholic drink) from +the Sweep 1 young person file, and use `count()` to tabulate the +variable before and after applying `negative_to_na()`. + +``` r +df_w1 <- read_dta("safeguarded_eul/wave_one_lsype_young_person_2020.dta", + col_select = c("NSID", "W1alceverYP")) + +df_w1 %>% + count(W1alceverYP) # Tabulates the raw variable +``` + + # A tibble: 7 × 2 + W1alceverYP n + + 1 -99 [YP not interviewed] 339 + 2 -97 [YP refused CASI section] 133 + 3 -96 [YP unable to complete CASI section] 102 + 4 -92 [Refused] 279 + 5 -1 [Don't know] 319 + 6 1 [Yes] 6740 + 7 2 [No] 7848 + +``` r +df_w1 %>% + mutate(W1alceverYP = negative_to_na(W1alceverYP)) %>% # Replaces negative values with NA + count(W1alceverYP) # Tabulates the cleaned variable +``` + + # A tibble: 3 × 2 + W1alceverYP n + + 1 1 [Yes] 6740 + 2 2 [No] 7848 + 3 NA 1172 + +In the second table, the negative values have been replaced with `NA`. +Note, `negative_to_na()` treats *every* negative value as missing, so it +should not be used with variables that can take genuinely negative +values. diff --git a/docs/next_steps-household_grid.md b/docs/next_steps-household_grid.md new file mode 100644 index 0000000..b4a7c0a --- /dev/null +++ b/docs/next_steps-household_grid.md @@ -0,0 +1,494 @@ +--- +layout: default +title: Working with the Household Grid +nav_order: 3 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + + +- [Download the R script for this + page](../purl/next_steps-household_grid.R) +- [Download the equivalent Stata script for this + page](../do_files/next_steps-household_grid.do) + +# Introduction + +In this section, we describe the basics of using the household grid. +Specifically, we show how to use the household grid to: + +1. Identify particular family members + +2. Create family-member specific variables + +3. Find out who the “main parent” and “second parent” are, and whether + these are the same people in each sweep + +4. Determine the relationships between other members of the household. + +We use the following packages: + +``` r +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +``` + +# Finding Mother of Cohort Members + +To show how to perform 1 & 2, we use the example of finding natural +mothers’ employment status at the first sweep. The household grids are +stored in their own subfolder, `household_grids`. The Sweep 1 household +grid (`household_grids/wave_one_lsype_household_grid_file_2020.dta`) has +one row for each member of the cohort member’s household, [including the +cohort member +themselves](https://cls-data.github.io/docs/next_steps-data_structures.html). +We load just five variables: `NSID` and `W1HhID`, which together +uniquely identify an individual, `W1Sex` and `W1R_1`, which contain +information on the individual’s sex and their relationship to the cohort +member, and `W1EmpStat`, which contains their employment status. + +`W1HhID` is the individual’s person number within the household. The +cohort member is always person number 1. The household grid records the +relationships between household members in the variables `W1R_1`, +`W1R_2`, …, `W1R_14`; the number at the end of the variable name is the +person number of the *other* household member. `W1R_1` therefore records +the relationship of the person in the row to person number 1 - that is, +to the cohort member. + +`W1R_1 == 8` identifies natural parents and `W1Sex == 2` identifies +females. Combining the two identifies natural mothers. Below, we use +`count()` to show the different (observed) values for the sex and +relationship variables. We also use the `filter()` function (which +retains observations where the conditions are `TRUE`) to create a +dataset containing natural mothers only. +`add_count(NSID) %>% filter(n == 1)` is included as an interim step to +ensure there is just one natural mother per family.[^1] + +``` r +df_w1_hhgrid <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, W1Sex, W1R_1, W1EmpStat) # Retains the listed variables + +df_w1_hhgrid %>% + count(W1Sex) # Tabulates each sex +``` + + # A tibble: 3 × 2 + W1Sex n + + 1 -999 [Missing household data] 104 + 2 1 [Male] 33916 + 3 2 [Female] 36573 + +``` r +df_w1_hhgrid %>% + count(W1R_1) # Tabulates each relationship to the cohort member +``` + + # A tibble: 22 × 2 + W1R_1 n + + 1 -999 [Missing household data] 104 + 2 -92 [Refused] 26 + 3 -91 [Not applicable] 15656 + 4 1 [Husband/ Wife] 1 + 5 3 [Natural son/ daughter] 3 + 6 5 [Foster child] 2 + 7 6 [Step-son/ Step-daughter] 1 + 8 8 [Natural parent] 24959 + 9 9 [Adoptive parent] 152 + 10 10 [Foster parent] 138 + # ℹ 12 more rows + +``` r +df_w1_mothers <- df_w1_hhgrid %>% + filter( + W1R_1 == 8, # Keep natural parents of the cohort member... + W1Sex == 2 # ...who are female. + ) %>% + add_count(NSID) %>% # Creates new variable (n) containing # of records with given NSID + filter(n == 1) %>% # Keep where only one recorded natural mother per family + select(NSID, W1HhID, W1EmpStat) # Keep identifier variables and employment status +``` + +Note, there is one cohort member per family in Next Steps. There is, +therefore, no ambiguity about which cohort member a relationship refers +to. + +# Creating a Mother’s Employment Variable + +Unlike in the [Millennium Cohort +Study](https://cls-data.github.io/docs/mcs-household_grid.html), the +Next Steps household grid holds several characteristics of each +household member, including their employment status (`W1EmpStat`), +marital status (`W1MarStat`) and ethnic group (`W1EthGrp`). Having +identified natural mothers, we can therefore create a variable for +whether the cohort member’s mother is in paid work directly. `W1EmpStat` +takes the values `1` and `2` for individuals in full-time and part-time +paid work, respectively, and values between `3` and `9` for other +statuses (e.g., looking after the family or household). Below, we use +`case_when()` to create a binary variable, `mother_works`, and use +`count()` to tabulate the number and proportion of mothers who are and +are not in paid work. + +``` r +df_w1_mothers %>% + count(W1EmpStat) +``` + + # A tibble: 13 × 2 + W1EmpStat n + + 1 -92 [Refused] 3 + 2 -91 [Not applicable] 51 + 3 1 [Doing paid work for 30 or more hours a week] 4727 + 4 2 [Doing paid work for fewer than 30 hours a week] 4649 + 5 3 [Unemployed/ Looking for a job] 212 + 6 4 [On a training course or scheme] 86 + 7 5 [In full-time education/ at school] 155 + 8 6 [Looking after the family/ household] 4510 + 9 7 [Retired from work altogether] 22 + 10 8 [Sick/ disabled] 256 + 11 9 [Other] 79 + 12 11 3 + 13 12 [Not Stated] 2 + +``` r +df_w1_mother_works <- df_w1_mothers %>% + mutate(mother_works = case_when(W1EmpStat %in% 1:2 ~ 1, # If W1EmpStat is 1 or 2, then 1 + W1EmpStat %in% 3:9 ~ 0)) %>% # If W1EmpStat is between 3 and 9, then 0 + select(NSID, mother_works) + +df_w1_mother_works %>% + count(mother_works) %>% + mutate(prop = n / sum(n)) +``` + + # A tibble: 3 × 3 + mother_works n prop + + 1 0 5320 0.361 + 2 1 9376 0.635 + 3 NA 59 0.00400 + +The result is a dataset with one row per family with an identified +natural mother, which can be merged with other cohort member-level +datasets using `NSID`. Note, the family background files contain derived +variables for some characteristics of the cohort member’s mother and +father (in this case, `W1empsmum` and `W1empsdad` in +`safeguarded_eul/wave_one_lsype_family_background_2020.dta`). The +approach shown here is needed where a derived variable is not available, +or where you are interested in other family members, such as siblings or +grandparents. + +# Identifying the Main and Second Parent + +In Sweeps 1-4, [interviews were conducted with a “main parent” and a +“second +parent”](https://cls-data.github.io/docs/next_steps-data_structures.html). +Variables relating to these individuals are suffixed `MP` and `SP` (for +example, `W1hiqualgMP` and `W1hiqualgSP` in +`safeguarded_eul/wave_one_lsype_family_background_2020.dta`). To +interpret these variables, it is helpful to know who the main and second +parent are. + +The household grid contains the variables `W1mainres` and `W1secores`, +which record the person numbers of the main parent and second parent, +respectively. These variables take the same value for every member of a +household. Below, we create a variable, `role`, by comparing each +individual’s person number (`W1HhID`) to these variables, and keep the +rows for individuals who are either the main or second parent. We then +tabulate the sex of main and second parents and their relationship to +the cohort member. `as_factor()` (from `haven`) converts the `labelled` +variables to factors so that value labels, rather than numeric values, +are displayed. + +``` r +df_w1_parents <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, W1Sex, W1R_1, W1mainres, W1secores) %>% + mutate(role = case_when(W1HhID == W1mainres ~ "Main parent", + W1HhID == W1secores ~ "Second parent")) %>% + drop_na(role) # Drops rows for individuals who are not the main or second parent + +df_w1_parents %>% + mutate(across(c(W1Sex, W1R_1), as_factor)) %>% + count(role, W1Sex, W1R_1) %>% + print(n = Inf) # Prints all rows +``` + + # A tibble: 33 × 4 + role W1Sex W1R_1 n + + 1 Main parent Male Natural parent 2598 + 2 Main parent Male Adoptive parent 16 + 3 Main parent Male Foster parent 11 + 4 Main parent Male Step-parent 79 + 5 Main parent Male Natural brother/ sister 34 + 6 Main parent Male Half-brother/ -sister 1 + 7 Main parent Male Brother-in-law/ Sister-in-law 1 + 8 Main parent Male Grandparent 16 + 9 Main parent Male Other relative 12 + 10 Main parent Male Other non-relative 2 + 11 Main parent Female Refused 4 + 12 Main parent Female Natural parent 12485 + 13 Main parent Female Adoptive parent 62 + 14 Main parent Female Foster parent 71 + 15 Main parent Female Step-parent 61 + 16 Main parent Female Parent-in-law/ Partner's parent 1 + 17 Main parent Female Natural brother/ sister 36 + 18 Main parent Female Half-brother/ -sister 1 + 19 Main parent Female Foster brother/ Foster sister 1 + 20 Main parent Female Brother-in-law/ Sister-in-law 1 + 21 Main parent Female Grandparent 85 + 22 Main parent Female Other relative 35 + 23 Main parent Female Other non-relative 9 + 24 Second parent Male Natural parent 7544 + 25 Second parent Male Adoptive parent 60 + 26 Second parent Male Foster parent 45 + 27 Second parent Male Step-parent 1263 + 28 Second parent Male Natural brother/ sister 5 + 29 Second parent Female Natural parent 2218 + 30 Second parent Female Adoptive parent 11 + 31 Second parent Female Foster parent 9 + 32 Second parent Female Step-parent 111 + 33 Second parent Female Natural brother/ sister 1 + +`df_w1_parents` has one row per parent. It can be used to create +variables for a specific type of parent from the `MP` and `SP` +variables. We show an example of this in [*Combining Data Within A +Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html). + +## Changes in the Main and Second Parent Across Sweeps + +The main and second parent are roles in the interview rather than fixed +individuals: the person interviewed as the main parent in one sweep is +not necessarily the person interviewed as the main parent in the next. +This matters when using `MP` and `SP` variables from more than one +sweep. + +A household member is intended to keep the same person number in each +sweep, so we can check whether the main parent has changed by comparing +the person number of the main parent across sweeps. Below, we do this +for Sweeps 1 and 2. For each sweep, we create a dataset containing the +row for the main parent from that sweep’s household grid, keeping their +person number. (The Sweep 2 household grid, +`household_grids/wave_two_lsype_household_grid_file_2020.dta`, contains +equivalent variables to the Sweep 1 grid, with the prefix `W2` rather +than `W1`.) We use `zap_labels()` (from `haven`) to remove the value +labels from the person numbers, leaving standard numeric variables that +can be compared directly. + +``` r +df_w1_main <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + filter(W1HhID == W1mainres) %>% # Keeps the row for the main parent + mutate(w1_main_hhid = zap_labels(W1HhID)) %>% # Removes value labels + select(NSID, w1_main_hhid) + +df_w2_main <- read_dta("household_grids/wave_two_lsype_household_grid_file_2020.dta") %>% + filter(W2HhID == W2mainres) %>% + mutate(w2_main_hhid = zap_labels(W2HhID)) %>% + select(NSID, w2_main_hhid) +``` + +We then merge the two datasets using `inner_join()`, so that we keep the +families where a main parent was identified in both sweeps, and tabulate +whether the main parent has the same person number in the two sweeps. + +``` r +df_main <- df_w1_main %>% + inner_join(df_w2_main, by = "NSID") + +df_main %>% + count(same_person = w1_main_hhid == w2_main_hhid) +``` + + # A tibble: 2 × 2 + same_person n + + 1 FALSE 1223 + 2 TRUE 12212 + +Where the main parent is not the same person in the two sweeps, a +variable such as `W2hiqualgMP` describes a different person to +`W1hiqualgMP`. Where this matters for your analysis, you could restrict +the sample to families where the main parent is unchanged, or use the +approach shown above to create variables for a particular parent (e.g., +the mother) in each sweep. + +# Determining Relationships between Other Household Members + +So far we have only used `W1R_1`, the relationship of each household +member to the cohort member. The remaining relationship variables +(`W1R_2` to `W1R_14`) can be used to identify the relationships between +other members of the household. Specifically, they record the person in +the row’s (ego) relationship to the person denoted by the column +(alter); the number at the end of the variable name corresponds to the +alter’s `W1HhID`. For instance, the variable `W1R_2` denotes the +relationship of the person in the row to the person in the same +household with `W1HhID == 2`. Below, we extract a small set of data from +the Sweep 1 household grid to show this in action. + +``` r +df_w1_hhgrid_rel <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, matches("^W1R_\\d+$")) + +df_w1_hhgrid_rel %>% + filter(NSID == first(NSID)) %>% # To look at just one household + select(W1HhID, W1R_1, W1R_2, W1R_3) # To look at first few relationship variables +``` + + # A tibble: 4 × 4 + W1HhID W1R_1 W1R_2 W1R_3 + + 1 1 -91 [Not applicable] -91 [Not applicable] -91 [Not … + 2 2 8 [Natural parent] -91 [Not applicable] -91 [Not … + 3 3 11 [Step-parent] 1 [Husband/ Wife] -91 [Not … + 4 4 13 [Natural brother/ sister] 3 [Natural son/ daughter] 6 [Step… + +Each row shows the relationships of one household member to the first +three people in the household. For instance, where the person with +`W1HhID == 2` is the natural parent of the cohort member, their row has +`W1R_1 == 8 [Natural parent]`. Note, each relationship is only recorded +once, in the row of the person with the *higher* person number: a +relationship variable is only filled in where the individual’s `W1HhID` +is greater than the number at the end of the variable name, and is +otherwise coded as not applicable (`-91`). `W1R_2`, for instance, is +only filled in for individuals with a `W1HhID` of 3 or more, and every +relationship variable is coded as not applicable for the cohort member +(`W1HhID == 1`). The relationship in the other direction is not recorded +and has to be inferred - if the person with `W1HhID == 2` is the natural +parent of the cohort member, then the cohort member is the natural child +of that person. + +If we want to find the particular person occupying a specific +relationship for an individual (e.g., we want to know the `W1HhID` of +the person’s partner), we need to reshape the data into long-format with +one row per ego-alter relationship within a household (for more on +reshaping data, see [*Reshaping Data from Long to Wide (or Wide to +Long)*](https://cls-data.github.io/docs/next_steps-reshape_long_wide.html)). +For instance, to find the individuals who are spouses or partners, we +can do the following: + +``` r +df_w1_couples <- df_w1_hhgrid_rel %>% + pivot_longer(cols = matches("^W1R_\\d+$"), + names_to = "W1HhID_alter", + names_prefix = "W1R_", # Removes "W1R_" from the names, leaving the alter's person number + names_transform = as.integer, # Converts the alter's person number to an integer + values_to = "relationship") %>% + filter(relationship %in% 1:2) %>% # Keep where husband/wife or partner/cohabitee + mutate(W1HhID = as.integer(W1HhID)) %>% # Converts the person number to an integer (removing its value labels) + select(NSID, W1HhID, partner_hhid = W1HhID_alter) + +df_w1_couples +``` + + # A tibble: 11,709 × 3 + NSID W1HhID partner_hhid + + 1 NS23533L 3 2 + 2 NS24676Q 3 2 + 3 NS21482P 3 2 + 4 NS25978V 3 2 + 5 NS23018R 3 2 + 6 NS21572X 3 2 + 7 NS21185L 3 2 + 8 NS13972M 3 2 + 9 NS20913T 3 2 + 10 NS14531V 3 2 + # ℹ 11,699 more rows + +As each relationship is only recorded once, `df_w1_couples` has one row +per *couple*, with the partner with the higher person number in the +`W1HhID` column. To find each person’s spouse or partner (conditional on +one being present), both members of a couple need a row. Below, we +create a copy of the dataset in which the person numbers of the two +partners are swapped, and append this to the original using +`bind_rows()`. Swapping the person numbers is sufficient here as the +relationship is the same in both directions; for other relationships +(e.g., parent and child), the relationship itself would also need to be +recoded. + +``` r +df_w1_couples_rev <- df_w1_couples %>% + select(NSID, W1HhID = partner_hhid, partner_hhid = W1HhID) # Swaps the person numbers of the two partners + +bind_rows(df_w1_couples, df_w1_couples_rev) %>% # Appends the two datasets + arrange(NSID, W1HhID) # Sorts the dataset by ID and person number +``` + + # A tibble: 23,418 × 3 + NSID W1HhID partner_hhid + + 1 NS10001S 2 3 + 2 NS10001S 3 2 + 3 NS10002T 2 3 + 4 NS10002T 3 2 + 5 NS10003V 2 3 + 6 NS10003V 3 2 + 7 NS10004W 2 3 + 8 NS10004W 3 2 + 9 NS10005X 2 3 + 10 NS10005X 3 2 + # ℹ 23,408 more rows + +# Coda + +This only scratches the surface of what can be achieved with the +household grid. A few further points are worth noting: + +- The household grids for Sweeps 2-4 + (`wave_[two-four]_lsype_household_grid_file_2020.dta`) have a similar + structure to the Sweep 1 grid. The relationship variables (`W2R_1`, + `w3R_1`, `W4R_1`, and so on) follow the same rule: each relationship + is only recorded once, in the row of the person with the higher person + number. Variable names differ in their use of upper and lower case, + however: for instance, the person number is `W2HhID` in Sweep 2, + `w3HhID` in Sweep 3 and `W4hhid` in Sweep 4.[^2] These grids also + include people who have left the household since an earlier sweep; the + variables `W2SHGInt`, `w3SHGint` and `W4SHGint` record whether a + person is still living with the cohort member. +- From Sweep 5, the household grid was completed by the cohort member + and is much less detailed. The Sweep 5-7 grids + (`wave_[five-seven]_lsype_household_grid_file_2020.dta`) contain a + single variable recording a simplified relationship to the cohort + member (e.g., `W5RELATION`), and the main and second parent are no + longer identified. The person number is named `HHID` in these files. + Note, at Sweep 7, `W7RELATION` is only filled in for people who are + new to the household at that sweep + (`W7SHGINT == 2 [Present - New at current wave]`) and is coded + `-91 [Not applicable]` for everyone else; at Sweeps 5 and 6, the + relationship is recorded for all people present in the household (this + is not documented in the user guide). For people who were already in + the household at Sweep 7, the relationship to the cohort member + therefore needs to be taken from the Sweep 5 or 6 grid, by matching on + `NSID` and `HHID`. +- At Sweeps 8 and 9, information on the people the cohort member lives + with is contained in `ns8_2015_household_members.dta` and + `ns9_2022_person_grid.dta` (both also in the `household_grids` + subfolder). These files do not include a row for the cohort member, + and the relationship to the cohort member is recorded in the variables + `W8RELTOKEY` and `W9RELTOKEY`, respectively. + +# Footnotes + +[^1]: Loading the `.dta` files into `R` with `haven::read_dta()` retains + the dataset metadata, including variable names and labels, mainly by + storing variables as `labelled` class objects. See the [`labelled` + package help + files](https://cran.r-project.org/web/packages/labelled/vignettes/intro_labelled.html) + for more information on working with this metadata - for instance, + converting `labelled` variables to standard `R` factor variables or + replacing negative values (generally reserved in Next Steps data to + indicate missingness) with `R`’s native `NA` value. + +[^2]: `rename_with()` can be used to rename variables *en masse* so that + they follow the same rubric. For instance, + `rename_with(str_to_upper)` converts every variable name in a + dataset to upper case, so that the person number would be named + `W2HHID`, `W3HHID` and `W4HHID` in Sweeps 2, 3 and 4, respectively. + See [*Combining Data Across + Sweeps*](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html) + for more on `rename_with()`. diff --git a/docs/next_steps-merging_across_sweeps.md b/docs/next_steps-merging_across_sweeps.md new file mode 100644 index 0000000..e27fd7f --- /dev/null +++ b/docs/next_steps-merging_across_sweeps.md @@ -0,0 +1,632 @@ +--- +layout: default +title: Combining Data Across Sweeps +nav_order: 4 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + + +- [Download the R script for this + page](../purl/next_steps-merging_across_sweeps.R) +- [Download the equivalent Stata script for this + page](../do_files/next_steps-merging_across_sweeps.do) + +# Introduction + +In this section, we show how to combine Next Steps data across sweeps, +assuming the data to be merged have one row per cohort member; for +information on restructuring data that are not in this format see the +page [*Combining Data Within A +Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html). + +As an example, we use data on cohort members’ GHQ-12 scores (a measure +of psychological distress), which were recorded in Sweeps 2, 4, 8 and 9 +(ages 15, 17, 25 and 32). The scores are available in the Sweep 2 and 4 +young person files (`wave_two_lsype_young_person_2020.dta` and +`wave_four_lsype_young_person_2020.dta`) and the Sweep 8 and 9 derived +variable files (`ns8_2015_derived.dta` and +`ns9_2022_derived_variables.dta`). These files contain one row per +cohort member. All four are stored in the `safeguarded_eul` subfolder. + +We begin by combining data from the second and fourth sweeps, showing +how to combine these datasets in **wide** (one row per observational +unit) and **long** (multiple rows per observational unit) formats by +*merging* and *appending*, respectively. We then show how to combine +data from multiple sweeps *programmatically* using the `dplyr` and +`purrr` packages (from the `tidyverse`). This requires a little more +preparation than in, e.g., the +[MCS](https://cls-data.github.io/docs/mcs-merging_across_sweeps.html), +as the names of files and variables do not follow a single convention +across the whole study. + +We use the following packages: + +``` r +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For handling missing values +``` + +# Merging Across Sweeps + +The variables `W2ghq12scr` and `W4ghq12scr` contain the cohort member’s +GHQ-12 score at Sweep 2 and Sweep 4, respectively. [Variable names in +Next Steps begin with a prefix denoting the +sweep](https://cls-data.github.io/docs/next_steps-data_structures.html) +(`W2`, `W4`), and in this case the rest of the name is the same in the +two sweeps. Cohort members are identified with a single variable, +`NSID`, which has the same name in every file. We will use the +`read_dta()` function from `haven` to read in the data from the second +and fourth sweeps, specifying the `col_select` argument to keep only the +variables we need (the identifier and GHQ-12 score). + +``` r +df_w2 <- read_dta("safeguarded_eul/wave_two_lsype_young_person_2020.dta", + col_select = c("NSID", "W2ghq12scr")) + +df_w4 <- read_dta("safeguarded_eul/wave_four_lsype_young_person_2020.dta", + col_select = c("NSID", "W4ghq12scr")) +``` + +We can merge these datasets by row using the `*_join()` family of +functions. These share a common syntax. They take two data frames (`x` +and `y`) as arguments, as well as a `by` argument that specifies the +variable(s) to join on. The `*_join()` functions are: + +1. `full_join(x, y)`: Returns all rows from `x` and `y`, and all + columns from `x` and `y`. For rows without matches in both `x` and + `y`, the missing value `NA` is used for columns that are not used as + identifiers. +2. `inner_join(x, y)`: Returns all rows from `x` and `y` where there + are matching rows in both data frames. +3. `left_join(x, y)`: Returns all rows from `x`, and all columns from + `x` and `y`. Rows in `x` with no match in `y` will have `NA` values + in the new columns from `y`. +4. `right_join(x, y)`: Returns all rows from `y`, and all columns from + `x` and `y`. Rows in `y` with no match in `x` will have `NA` values + in the columns of `x`. + +In the current context, where `x` is data from the second sweep +(`df_w2`) and `y` is data from the fourth sweep (`df_w4`), and these +datasets only contain rows for *respondents*: `full_join()` will return +a row for each individual present in the second or fourth sweeps, with +the GHQ-12 score from each sweep in the same row; `inner_join()` will +return a row for each individual who was present in both sweeps, with +the GHQ-12 score from each sweep in the same row; `left_join()` will +return a row for each individual in the second sweep, with the GHQ-12 +score from the fourth sweep in the same row if the individual was +present in the fourth sweep; `right_join()` will return a row for each +individual in the fourth sweep, with the GHQ-12 score from the second +sweep in the same row if the individual was present in the second sweep. + +To specify the identifier, we pass its name to the `by` argument. The +`*_join()` functions can also handle multiple variables to join on, as +well as situations where the identifiers have different names across `x` +and `y`, but neither is necessary here. + +``` r +df_w2 %>% + full_join(df_w4, by = "NSID") +``` + + # A tibble: 13,885 × 3 + NSID W2ghq12scr W4ghq12scr + + 1 NS10001S -92 [Refused] 0 + 2 NS10002T 3 5 + 3 NS10003V 0 0 + 4 NS10004W 4 1 + 5 NS10005X 2 NA + 6 NS10006Y 0 0 + 7 NS10007Z 2 0 + 8 NS10008A 0 3 + 9 NS10010L 0 NA + 10 NS10011M 0 5 + # ℹ 13,875 more rows + +``` r +df_w2 %>% + inner_join(df_w4, by = "NSID") +``` + + # A tibble: 11,436 × 3 + NSID W2ghq12scr W4ghq12scr + + 1 NS10001S -92 [Refused] 0 + 2 NS10002T 3 5 + 3 NS10003V 0 0 + 4 NS10004W 4 1 + 5 NS10006Y 0 0 + 6 NS10007Z 2 0 + 7 NS10008A 0 3 + 8 NS10011M 0 5 + 9 NS10014Q 1 0 + 10 NS10019W 0 0 + # ℹ 11,426 more rows + +``` r +df_w2 %>% + left_join(df_w4, by = "NSID") +``` + + # A tibble: 13,530 × 3 + NSID W2ghq12scr W4ghq12scr + + 1 NS10001S -92 [Refused] 0 + 2 NS10002T 3 5 + 3 NS10003V 0 0 + 4 NS10004W 4 1 + 5 NS10005X 2 NA + 6 NS10006Y 0 0 + 7 NS10007Z 2 0 + 8 NS10008A 0 3 + 9 NS10010L 0 NA + 10 NS10011M 0 5 + # ℹ 13,520 more rows + +``` r +df_w2 %>% + right_join(df_w4, by = "NSID") +``` + + # A tibble: 11,791 × 3 + NSID W2ghq12scr W4ghq12scr + + 1 NS10001S -92 [Refused] 0 + 2 NS10002T 3 5 + 3 NS10003V 0 0 + 4 NS10004W 4 1 + 5 NS10006Y 0 0 + 6 NS10007Z 2 0 + 7 NS10008A 0 3 + 8 NS10011M 0 5 + 9 NS10014Q 1 0 + 10 NS10019W 0 0 + # ℹ 11,781 more rows + +Note, the `*_join()` functions will merge any matching rows. Unlike +`Stata`, we do not have to explicitly state whether we want a 1-to-1, +many-to-1, 1-to-many, or many-to-many merge. This is determined by the +data that are inputted to `*_join()`. `R` will not throw an error if +matches are not 1-to-1 (though it does throw a warning where matches are +many-to-many), so care must be taken, for instance, when merging files +with different structures. See [*Combining Data Within A +Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html) +for more information. + +# Appending Sweeps + +To put the data into long format, we can use the `bind_rows()` function. +(In this case, the data will have one row per cohort-member x sweep +combination.) To work properly, we need to name the variables +consistently across sweeps, which here means removing the sweep-specific +prefixes (e.g., the `W2` from `W2ghq12scr` in `df_w2`). We also need to +add a variable to identify the sweep the data comes from. Below, we use +the `mutate()` function to create a `sweep` variable and then use the +`rename_with()` function to remove the prefixes and rename the variables +consistently across sweeps. + +``` r +df_w2_noprefix <- df_w2 %>% + mutate(sweep = 2, .before = 1) %>% + rename_with(~ str_remove(.x, "^W2")) + +df_w4_noprefix <- df_w4 %>% + mutate(sweep = 4, .before = 1) %>% + rename_with(~ str_remove(.x, "^W4")) +``` + +`rename_with()` applies a function to the names of the variables. In +this case, we use the `str_remove()` function from the `stringr` package +(part of the `tidyverse`) to remove the prefix from the variable names. +The `~` symbol is used to create an [*anonymous +function*](https://r4ds.hadley.nz/iteration.html), which is applied to +each variable name. The `.x` symbol in the anonymous function is a +placeholder for the variable name. `str_remove()` takes a regular +expression. The `^` symbol is used to match the start of the string (so +`^W2` removes `W2` where these are the first characters in a variable +name). Note, for the `mutate()` call, the `.before` argument is used to +specify the position of the new variable in the data frame - here we +specify `sweep` as the first column. Below we see what the formatted +data frames look like: + +``` r +df_w2_noprefix +``` + + # A tibble: 13,530 × 3 + sweep NSID ghq12scr + + 1 2 NS10001S -92 [Refused] + 2 2 NS10002T 3 + 3 2 NS10003V 0 + 4 2 NS10004W 4 + 5 2 NS10005X 2 + 6 2 NS10006Y 0 + 7 2 NS10007Z 2 + 8 2 NS10008A 0 + 9 2 NS10010L 0 + 10 2 NS10011M 0 + # ℹ 13,520 more rows + +``` r +df_w4_noprefix +``` + + # A tibble: 11,791 × 3 + sweep NSID ghq12scr + + 1 4 NS10001S 0 + 2 4 NS10002T 5 + 3 4 NS10003V 0 + 4 4 NS10004W 1 + 5 4 NS10006Y 0 + 6 4 NS10007Z 0 + 7 4 NS10008A 3 + 8 4 NS10011M 5 + 9 4 NS10014Q 0 + 10 4 NS10019W 0 + # ℹ 11,781 more rows + +Now the data have been prepared, we can use `bind_rows()` to append the +data frames together. This will stack the data frames on top of each +other, so the number of rows is equal to the sum of rows in the +individual datasets. The `bind_rows()` function can handle data frames +with different numbers of columns. Missing columns are filled with `NA` +values. + +``` r +bind_rows(df_w2_noprefix, df_w4_noprefix) %>% + arrange(NSID, sweep) # Sorts the dataset by ID and sweep +``` + + # A tibble: 25,321 × 3 + sweep NSID ghq12scr + + 1 2 NS10001S -92 [Refused] + 2 4 NS10001S 0 + 3 2 NS10002T 3 + 4 4 NS10002T 5 + 5 2 NS10003V 0 + 6 4 NS10003V 0 + 7 2 NS10004W 4 + 8 4 NS10004W 1 + 9 2 NS10005X 2 + 10 2 NS10006Y 0 + # ℹ 25,311 more rows + +Notice that with `bind_rows()` a cohort member has only as many rows of +data as the times they appeared in Sweeps 2 and 4. This differs from +`*_join()` where an explicit missing `NA` value is generated for the +missing sweep. The `tidyverse` function `complete()` [can be used to +create missing +rows](https://r4ds.hadley.nz/missing-values.html#sec-missing-implicit), +which can be useful if you need to generate a balanced panel of +observations from which to begin analysis with (e.g., when performing +multiple imputation in long format). + +``` r +bind_rows(df_w2_noprefix, df_w4_noprefix) %>% + complete(NSID, sweep) %>% # Ensure cohort members have a row for each sweep + arrange(NSID, sweep) +``` + + # A tibble: 27,770 × 3 + NSID sweep ghq12scr + + 1 NS10001S 2 -92 [Refused] + 2 NS10001S 4 0 + 3 NS10002T 2 3 + 4 NS10002T 4 5 + 5 NS10003V 2 0 + 6 NS10003V 4 0 + 7 NS10004W 2 4 + 8 NS10004W 4 1 + 9 NS10005X 2 2 + 10 NS10005X 4 NA + # ℹ 27,760 more rows + +Note, `rename_with()` can also be used to ensure that variables use the +same case in each sweep - for instance, `rename_with(str_to_upper)` +converts every variable name in a dataset to upper case. This is useful +in Next Steps as the use of upper and lower case in variable names +sometimes varies in hard-to-predict ways across sweeps (e.g., +`W1alceverYP` and `W4AlcEverYP`). + +# Combining Sweeps Programmatically + +Combining sweeps manually can become tedious when more than two sweeps +need to be combined. Instead, [iterative +programming](https://r4ds.hadley.nz/iteration) can be used to automate +the process. Below we show how to merge and append multiple sweeps +together with very little code using the `purrr` package (part of the +`tidyverse`). + +In some studies, file and variable names follow a formula, so the name +of the file and variable for a given sweep can be constructed from the +sweep number. This is not the case in Next Steps. The sweep is written +as a word in the names of files from Sweeps 1-7 (`wave_two_...`) and as +a number in the names of files from Sweeps 8 and 9 (`ns8_...`), and the +GHQ-12 score is named `W2ghq12scr` and `W4ghq12scr` in Sweeps 2 and 4 +but `W8DGHQSC` and `W9DGHQSC` in Sweeps 8 and 9. A simple way of +handling this is to create a lookup table that lists the file and +variable to use for each sweep. Below, we create one using the +`tribble()` function, which allows a `tibble` to be written out +row-by-row. Note, the `file` column includes the subfolder in which each +file is stored. (See [*Data +Discovery*](https://cls-data.github.io/docs/next_steps-data_discovery.html) +for ways of finding the names of the files and variables you need.) + +``` r +df_files <- tribble( + ~sweep, ~file, ~ghq_var, + 2, "safeguarded_eul/wave_two_lsype_young_person_2020.dta", "W2ghq12scr", + 4, "safeguarded_eul/wave_four_lsype_young_person_2020.dta", "W4ghq12scr", + 8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC", + 9, "safeguarded_eul/ns9_2022_derived_variables.dta", "W9DGHQSC" +) + +df_files +``` + + # A tibble: 4 × 3 + sweep file ghq_var + + 1 2 safeguarded_eul/wave_two_lsype_young_person_2020.dta W2ghq12scr + 2 4 safeguarded_eul/wave_four_lsype_young_person_2020.dta W4ghq12scr + 3 8 safeguarded_eul/ns8_2015_derived.dta W8DGHQSC + 4 9 safeguarded_eul/ns9_2022_derived_variables.dta W9DGHQSC + +## Merging Programmatically + +Before merging the datasets together, we need to load the data for each +sweep. We can do this by creating a function, `load_ghq_wide()`, which +takes three arguments - `sweep`, `file`, and `ghq_var` - corresponding +to the columns of `df_files`, and loads the GHQ-12 data from the +specified file. The `col_select` argument is again used to keep only the +variables we need. As the name of the GHQ-12 variable is stored in an +object (`ghq_var`), we wrap the names in `all_of()`, which tells +`read_dta()` to select the variables whose names are stored in the +vector. + +``` r +load_ghq_wide <- function(sweep, file, ghq_var){ + read_dta(file, col_select = all_of(c("NSID", ghq_var))) +} +``` + +To confirm the function is working correctly, below we call it to load +data from the eighth sweep. + +``` r +load_ghq_wide(8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC") +``` + + # A tibble: 7,705 × 2 + NSID W8DGHQSC + + 1 NS10001S 0 + 2 NS10004W 6 + 3 NS10011M 3 + 4 NS10020F 0 + 5 NS10021G 2 + 6 NS10026M 5 + 7 NS10027N 0 + 8 NS10029Q -1 [Not applicable] + 9 NS10030A 2 + 10 NS10031B 0 + # ℹ 7,695 more rows + +We could manually load and merge successively using multiple +`load_ghq_wide()` and `full_join()` function calls. However, this is +rather verbose: + +``` r +load_ghq_wide(2, "safeguarded_eul/wave_two_lsype_young_person_2020.dta", "W2ghq12scr") %>% + full_join(load_ghq_wide(4, "safeguarded_eul/wave_four_lsype_young_person_2020.dta", "W4ghq12scr"), + by = "NSID") %>% + full_join(load_ghq_wide(8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC"), + by = "NSID") %>% + full_join(load_ghq_wide(9, "safeguarded_eul/ns9_2022_derived_variables.dta", "W9DGHQSC"), + by = "NSID") +``` + + # A tibble: 14,586 × 5 + NSID W2ghq12scr W4ghq12scr W8DGHQSC W9DGHQSC + + 1 NS10001S -92 [Refused] 0 0 NA + 2 NS10002T 3 5 NA 0 + 3 NS10003V 0 0 NA NA + 4 NS10004W 4 1 6 0 + 5 NS10005X 2 NA NA NA + 6 NS10006Y 0 0 NA 7 + 7 NS10007Z 2 0 NA NA + 8 NS10008A 0 3 NA NA + 9 NS10010L 0 NA NA NA + 10 NS10011M 0 5 3 0 + # ℹ 14,576 more rows + +More efficiently, we can use the `pmap()` function from the `purrr` +package (part of the `tidyverse`) to apply the `load_ghq_wide()` +function to each row of `df_files` in turn. `pmap()` takes a data frame +(or list) as its first argument and a function to apply as its second +argument. It calls the function once per row of the data frame, matching +the columns of the data frame to the arguments of the function by name +(which is why the arguments of `load_ghq_wide()` have the same names as +the columns of `df_files`). `pmap()` returns the results as a `list`. +Below we use `pmap()` to run `load_ghq_wide()` for Sweeps 2, 4, 8 and 9. +To save space, we do not print the output. + +``` r +pmap(df_files, load_ghq_wide) +``` + +To merge the list of datasets returned by `pmap()` together, we can use +the `reduce()` function from `purrr`. `reduce()` takes an object as its +first argument, and a function as its second argument. It applies the +function to the first *two* elements of the object placed into the first +argument, and then successively applies the function to the result and +the third element of the list onwards, until the list is finished. +Below, we use `reduce()` to apply the `full_join()` function to the list +of data frames. We specify `full_join()` in an anonymous function. `.x` +and `.y` are the first and second inputs, respectively. In this case, at +the first iteration Sweep 2 (`.x`) is merged with Sweep 4 (`.y`), and at +the second iteration, the result of the first iteration (`.x`) is merged +with Sweep 8 (`.y`). This process is repeated until Sweep 9 has been +merged in. + +``` r +df_ghq_wide <- pmap(df_files, load_ghq_wide) %>% + reduce(~ full_join(.x, .y, by = "NSID")) + +df_ghq_wide +``` + + # A tibble: 14,586 × 5 + NSID W2ghq12scr W4ghq12scr W8DGHQSC W9DGHQSC + + 1 NS10001S -92 [Refused] 0 0 NA + 2 NS10002T 3 5 NA 0 + 3 NS10003V 0 0 NA NA + 4 NS10004W 4 1 6 0 + 5 NS10005X 2 NA NA NA + 6 NS10006Y 0 0 NA 7 + 7 NS10007Z 2 0 NA NA + 8 NS10008A 0 3 NA NA + 9 NS10010L 0 NA NA NA + 10 NS10011M 0 5 3 0 + # ℹ 14,576 more rows + +## Appending Programmatically + +To append the datasets together, we create a second function, +`load_ghq_long()`, to load the GHQ-12 data from a given sweep and format +it so that it can be appended to the other sweeps (i.e., giving +variables consistent names). As the GHQ-12 variable is not named +consistently across sweeps, removing the sweep prefix is not sufficient +here. Instead, we use `rename()` to give the variable a new name, +`ghq12`. We also add a variable identifying the sweep. Note, the GHQ-12 +scores are stored as `labelled` variables, with value labels attached to +the negative values that indicate different types of missing data. The +value labels (and the values used for missing data) differ between the +DfE and CLS eras, so we use `zap_labels()` (from `haven`) to remove the +labels, leaving a standard numeric variable. + +``` r +load_ghq_long <- function(sweep, file, ghq_var){ + read_dta(file, col_select = all_of(c("NSID", ghq_var))) %>% + rename(ghq12 = all_of(ghq_var)) %>% + mutate(ghq12 = zap_labels(ghq12), + sweep = sweep, .before = 1) +} +``` + +To load data from Sweeps 2, 4, 8 and 9 and append them together, we can +again use `pmap()` and pass the result to `bind_rows()`, which can take +a list of data frames as its input. As before, we use `arrange()` to +sort the dataset by ID and sweep. + +``` r +df_ghq_long <- pmap(df_files, load_ghq_long) %>% + bind_rows() %>% + arrange(NSID, sweep) # Sorts the dataset by ID and sweep + +df_ghq_long +``` + + # A tibble: 40,305 × 3 + sweep NSID ghq12 + + 1 2 NS10001S -92 + 2 4 NS10001S 0 + 3 8 NS10001S 0 + 4 2 NS10002T 3 + 5 4 NS10002T 5 + 6 9 NS10002T 0 + 7 2 NS10003V 0 + 8 4 NS10003V 0 + 9 2 NS10004W 4 + 10 4 NS10004W 1 + # ℹ 40,295 more rows + +Before using these data, the negative values would need to be replaced +with missing values (`NA`). Below, we do this with the +`negative_to_na()` function introduced in [*Data +Structures*](https://cls-data.github.io/docs/next_steps-data_structures.html#missing-values), +which uses the `labelled` package. + +``` r +negative_to_na <- function(x){ + na_range(x) <- c(-Inf, -1) + user_na_to_na(x) +} + +df_ghq_long %>% + mutate(ghq12 = negative_to_na(ghq12)) # Replaces negative values with NA +``` + + # A tibble: 40,305 × 3 + sweep NSID ghq12 + + 1 2 NS10001S NA + 2 4 NS10001S 0 + 3 8 NS10001S 0 + 4 2 NS10002T 3 + 5 4 NS10002T 5 + 6 9 NS10002T 0 + 7 2 NS10003V 0 + 8 4 NS10003V 0 + 9 2 NS10004W 4 + 10 4 NS10004W 1 + # ℹ 40,295 more rows + +# Coda: Defining the Sample with the Longitudinal File + +A cohort member only appears in a sweep’s files if they took part in +that sweep. The combined datasets created above therefore only include +cohort members who took part in at least one of the sweeps used, and do +not tell us *why* a cohort member has no data for a particular sweep. +This is especially relevant in Next Steps because [an ethnic minority +boost sample was added to the study at Sweep +4](https://cls-data.github.io/docs/next_steps-data_structures.html). +Boost sample members have no data for Sweeps 1-3 because they were not +yet part of the study, not because they did not respond. + +The file `safeguarded_eul/ns9_2022_longitudinal_file.dta` contains one +row for every cohort member, along with the fieldwork outcome at each +sweep (`W1OUTCOME`, `W2OUTCOME`, …, `W9OUTCOME`) and a variable +indicating whether the cohort member belongs to the original or boost +sample (`MAINBOOST`). (Boost sample members can also be identified with +the variable `W4Boost` in `wave_four_lsype_young_person_2020.dta`.) It +is good practice to begin with this file and merge other data onto it +with `left_join()`, so that the dataset contains all cohort members. +Below, we load the file, tabulate `MAINBOOST`, and merge on the wide +GHQ-12 dataset created above (latter output not shown). Note, we can use +regular expressions in `col_select` (via `matches()`) to select several +variables at once. + +``` r +df_longitudinal <- read_dta("safeguarded_eul/ns9_2022_longitudinal_file.dta", + col_select = c("NSID", "MAINBOOST", matches("^W\\dOUTCOME$"))) + +df_longitudinal %>% + count(MAINBOOST) +``` + + # A tibble: 2 × 2 + MAINBOOST n + + 1 1 [Main] 15770 + 2 2 [Boost] 352 + +``` r +df_longitudinal %>% + left_join(df_ghq_wide, by = "NSID") +``` + +The boost sample can then be dropped with `filter(MAINBOOST == 1)` +(`filter()` filters *in*) where an analysis uses data from Sweeps 1-3. diff --git a/docs/next_steps-merging_within_sweep.md b/docs/next_steps-merging_within_sweep.md new file mode 100644 index 0000000..33e0970 --- /dev/null +++ b/docs/next_steps-merging_within_sweep.md @@ -0,0 +1,323 @@ +--- +layout: default +title: Combining Data Within A Sweep +nav_order: 5 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + + +- [Download the R script for this + page](../purl/next_steps-merging_within_sweep.R) +- [Download the equivalent Stata script for this + page](../do_files/next_steps-merging_within_sweep.do) + +# Introduction + +In this section, we show how to merge, collapse and reshape the various +data structures within a given sweep of Next Steps to create a dataset +at the cohort member-level (i.e., one row per cohort member). This is +likely to be the most useful data structure for most analyses. + +[Most Next Steps files already have one row per cohort +member](https://cls-data.github.io/docs/next_steps-data_structures.html) +and all files are linked with a single identifier, `NSID`, so combining +data within a sweep is more straightforward than in, e.g., the +[MCS](https://cls-data.github.io/docs/mcs-merging_within_sweep.html). +There are two complications. First, information about cohort members’ +parents is stored in separate variables for the “main parent” and +“second parent”, so some work is required to create variables that +summarise both parents or that relate to a particular parent (such as +the mother). Second, a small number of files - notably the household +grid - have more than one row per cohort member and need to be collapsed +before they are merged with other data. + +We use the following packages: + +``` r +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +``` + +# Data Cleaning + +We create a small dataset that contains information from Sweep 1 on: the +cohort member’s sex and attitude to school, housing tenure, family +social class (National Statistics Socio-economic Classification; +NS-SEC), mother’s social class, and the number of siblings living with +the cohort member. Constructing and combining these variables involves +restructuring the data in various ways, and spans the most common data +engineering tasks involved in bringing together information from a +single sweep. + +The datasets we use in this tutorial are below. Note, the household grid +is stored in a different subfolder to the young person and family +background files. + +``` r +yp <- read_dta("safeguarded_eul/wave_one_lsype_young_person_2020.dta") # One row per cohort member +family <- read_dta("safeguarded_eul/wave_one_lsype_family_background_2020.dta") # One row per cohort member +hhgrid <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") # One row per household member +``` + +We begin with the simplest variables: the cohort member’s sex and their +attitude to school. These are stored in a cohort-member level dataset +already (`wave_one_lsype_young_person_2020`), so they do not need +further processing. Below we rename the relevant variables and select +them along with the cohort member identifier, `NSID`. + +``` r +df_yp <- yp %>% + select(NSID, sex = W1sexYP, school_attitude = W1yschat1) # Retains the listed variables, renaming W1sexYP as sex and W1yschat1 as school_attitude + +df_yp +``` + + # A tibble: 15,760 × 3 + NSID sex school_attitude + + 1 NS10001S 1 [Male] 22 + 2 NS10002T 2 [Female] 19 + 3 NS10003V 1 [Male] 26 + 4 NS10004W 2 [Female] 40 + 5 NS10005X 1 [Male] 27 + 6 NS10006Y 2 [Female] 38 + 7 NS10007Z 1 [Male] 43 + 8 NS10008A 2 [Female] 29 + 9 NS10009B 2 [Female] 20 + 10 NS10010L 1 [Male] 43 + # ℹ 15,750 more rows + +Housing tenure is a characteristic of the household and is stored in the +family background file (`wave_one_lsype_family_background_2020`). As +there is one cohort member per family in Next Steps, this file also has +one row per cohort member, and the variable does not need any further +processing at this stage. + +``` r +df_tenure <- family %>% + select(NSID, tenure = W1hous12HH) +``` + +Next, we create a variable for family social class using data on both +parents. The family background file contains the NS-SEC of the main +parent (`W1nssecMP`) and the second parent (`W1nssecSP`). As these are +stored in separate *columns* (rather than separate rows), we can create +a summary variable by operating across the columns. We first replace +values outside the range 1-8 with `NA` (negative values denote various +forms of missingness - for instance, `-98` indicates there is no second +parent in the household). We then take the minimum of the two variables +using `pmin()` (lower values of NS-SEC indicate higher social class). +`pmin()` returns the minimum for each row; the argument `na.rm = TRUE` +means that where NS-SEC is only available for one parent, that parent’s +value is used.[^1] + +``` r +df_nssec <- family %>% + select(NSID, W1nssecMP, W1nssecSP) %>% + mutate(across(c(W1nssecMP, W1nssecSP), + ~ if_else(between(.x, 1, 8), as.numeric(.x), NA))) %>% # Values outside 1-8 denote various forms of missingness + mutate(family_nssec = pmin(W1nssecMP, W1nssecSP, na.rm = TRUE)) %>% # Takes the lowest value of the two variables in each row + select(NSID, family_nssec) + +df_nssec +``` + + # A tibble: 15,760 × 2 + NSID family_nssec + + 1 NS10001S 2 + 2 NS10002T 1 + 3 NS10003V 6 + 4 NS10004W NA + 5 NS10005X 2 + 6 NS10006Y 7 + 7 NS10007Z 3 + 8 NS10008A 5 + 9 NS10009B 7 + 10 NS10010L 4 + # ℹ 15,750 more rows + +We next show a different way of using the main and second parent +variables: reshaping the data from wide to long so that we have one row +per *parent*. This is useful where we want to create a variable for a +particular parent - in this case, the cohort member’s mother. [The main +and second parent are roles in the +interview](https://cls-data.github.io/docs/next_steps-data_structures.html), +and either could be the cohort member’s mother, so we need to bring in +information from the household grid to find out who each parent is. + +The family background file contains the variables `W1mainres` and +`W1secores`, which record the person number of the main and second +parent in the household grid. Below, we first rename these variables so +that they follow the same convention as the NS-SEC variables (a common +stem, followed by `MP` or `SP`). We then reshape the data from [wide to +long using +`pivot_longer()`](https://r4ds.hadley.nz/data-tidy.html#sec-pivoting). +The `names_pattern` argument uses a regular expression to split the +variable names into two pieces: the stem (`"(.*)"`) and the suffix +(`"(MP|SP)"`). The stem is used to name the new columns (`.value`) and +the suffix is stored in a new variable, `parent`. The result is a +dataset with two rows per cohort member, one for each parent.[^2] + +``` r +df_parent <- family %>% + select(NSID, W1HhIDMP = W1mainres, W1HhIDSP = W1secores, W1nssecMP, W1nssecSP) %>% + zap_labels() %>% # Removes value labels + pivot_longer(cols = -NSID, # Reshape all columns except NSID + names_to = c(".value", "parent"), + names_pattern = "^(.*)(MP|SP)$") + +df_parent +``` + + # A tibble: 31,520 × 4 + NSID parent W1HhID W1nssec + + 1 NS10001S MP 2 7 + 2 NS10001S SP 3 2 + 3 NS10002T MP 2 1 + 4 NS10002T SP 3 6 + 5 NS10003V MP 2 6 + 6 NS10003V SP 3 7 + 7 NS10004W MP 2 -99 + 8 NS10004W SP 3 -99 + 9 NS10005X MP 3 6 + 10 NS10005X SP 2 2 + # ℹ 31,510 more rows + +`df_parent` now contains the person number of each parent (`W1HhID`). We +can use this to merge in each parent’s sex (`W1Sex`) and relationship to +the cohort member (`W1R_1`) from the household grid (see [*Working with +the Household +Grid*](https://cls-data.github.io/docs/next_steps-household_grid.html)). +We use `inner_join()` so that we only keep rows where the parent is +found in the household grid (this drops, for instance, rows for second +parents in families where there is no second parent). We then keep the +rows for natural mothers (`W1R_1 == 8` \[Natural parent\] and +`W1Sex == 2` \[Female\]). The result is a dataset with one row per +cohort member whose natural mother was the main or second parent, +containing the mother’s NS-SEC.[^3] + +``` r +df_mother_nssec <- hhgrid %>% + select(NSID, W1HhID, W1Sex, W1R_1) %>% + inner_join(df_parent, by = c("NSID", "W1HhID")) %>% + filter(W1R_1 == 8, # Keep natural parents... + W1Sex == 2) %>% # ...who are female + add_count(NSID) %>% # Creates new variable (n) containing # of records with given NSID + filter(n == 1) %>% # Keep where only one natural mother identified per cohort member + mutate(mother_nssec = if_else(between(W1nssec, 1, 8), W1nssec, NA)) %>% + select(NSID, mother_nssec) +``` + +Finally, we create a variable for the number of siblings living with the +cohort member. This involves collapsing the household grid, which has +one row per household member, so that it has one row per cohort member. +`W1R_1` records each household member’s relationship to the cohort +member, with values between 13 and 17 indicating different types of +sibling (natural, half-, step-, adopted and foster siblings). We count +the number of rows that meet this condition using `summarise()` on a +[grouped data frame](https://r4ds.hadley.nz/data-transform.html#groups) +(`group_by(NSID)`) to ensure this is calculated per cohort member. + +``` r +df_siblings <- hhgrid %>% + select(NSID, W1HhID, W1R_1) %>% + group_by(NSID) %>% # Groups the data so summarise() is performed per cohort member + summarise(n_siblings = sum(W1R_1 %in% 13:17), # Counts the number of rows where W1R_1 is between 13 and 17 + .groups = "drop") # Removes the grouping from the resulting dataframe + +df_siblings +``` + + # A tibble: 15,760 × 2 + NSID n_siblings + + 1 NS10001S 1 + 2 NS10002T 3 + 3 NS10003V 3 + 4 NS10004W 3 + 5 NS10005X 2 + 6 NS10006Y 2 + 7 NS10007Z 2 + 8 NS10008A 2 + 9 NS10009B 0 + 10 NS10010L 2 + # ℹ 15,750 more rows + +The same principles apply to the “hierarchical” files from Sweeps 8 and +9 - for instance, `ns8_2015_children.dta`, which has one row for each of +the cohort member’s children. Note, though, that cohort members only +appear in these files if they have at least one record (e.g., at least +one child), so some care is needed when merging the collapsed data with +other files: cohort members who do not appear in the file should +typically be assigned a count of zero, rather than `NA`. + +# Merging the Datasets + +Now we have cleaned each variable, we can merge them together. The +cleaned datasets are all at the cohort member level. We begin with +`df_yp` as this has all the cohort members participating at Sweep 1 in +it. We then use `left_join()` to merge in other data so original rows +are kept (and no more are added). As `NSID` uniquely identifies cohort +members, we use `left_join(..., by = "NSID")` in each case. + +``` r +df_yp %>% + left_join(df_tenure, by = "NSID") %>% + left_join(df_nssec, by = "NSID") %>% + left_join(df_mother_nssec, by = "NSID") %>% + left_join(df_siblings, by = "NSID") +``` + + # A tibble: 15,760 × 7 + NSID sex school_attitude tenure family_nssec mother_nssec n_siblings + + 1 NS10001S 1 [Mal… 22 2 [Bei… 2 7 1 + 2 NS10002T 2 [Fem… 19 1 [Own… 1 6 3 + 3 NS10003V 1 [Mal… 26 2 [Bei… 6 6 3 + 4 NS10004W 2 [Fem… 40 2 [Bei… NA NA 3 + 5 NS10005X 1 [Mal… 27 2 [Bei… 2 6 2 + 6 NS10006Y 2 [Fem… 38 4 [Ren… 7 7 2 + 7 NS10007Z 1 [Mal… 43 2 [Bei… 3 3 2 + 8 NS10008A 2 [Fem… 29 2 [Bei… 5 5 2 + 9 NS10009B 2 [Fem… 20 2 [Bei… 7 7 0 + 10 NS10010L 1 [Mal… 43 2 [Bei… 4 6 2 + # ℹ 15,750 more rows + +As noted in [*Combining Data Across +Sweeps*](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html), +`left_join()` will not throw an error if a cohort member appears more +than once in one of the datasets - it will simply add rows. If you want +`R` to enforce that each row is matched to at most one row in the other +dataset, you can add the argument `relationship = "one-to-one"` to the +`*_join()` function call. + +# Footnotes + +[^1]: `wave_one_lsype_family_background_2020` also contains a derived + variable for family NS-SEC, `W1nssecfam`, which is instead based on + the occupation of the household reference person. We create our own + variable here to demonstrate the principle, which can be applied to + any pair of `MP` and `SP` variables. + +[^2]: We use `zap_labels()` to remove value labels from the variables + prior to reshaping. `pivot_longer()` stacks the main and second + parent variables on top of each other, and will print a warning + where their value labels are not identical. For more on reshaping + data, see [*Reshaping Data from Long to Wide (or Wide to + Long)*](https://cls-data.github.io/docs/next_steps-reshape_long_wide.html). + +[^3]: More detail on merging with `inner_join()` (and other `*_join()` + variants) is provided in [*Combining Data Across + Sweeps*](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html), + as well as [Chapter 19 of the R for Data Science + textbook](https://r4ds.hadley.nz/joins.html#sec-mutating-joins). + Note, for many characteristics, the family background file already + contains derived variables for mothers and fathers - in this case, + `W1nssecmum` and `W1nssecdad`. The approach here is needed for `MP` + and `SP` variables that do not have such an equivalent. diff --git a/docs/next_steps-reshape_long_wide.md b/docs/next_steps-reshape_long_wide.md new file mode 100644 index 0000000..3e8aeab --- /dev/null +++ b/docs/next_steps-reshape_long_wide.md @@ -0,0 +1,315 @@ +--- +layout: default +title: Reshaping Data from Long to Wide (or Wide to Long) +nav_order: 6 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + + +- [Download the R script for this + page](../purl/next_steps-reshape_long_wide.R) +- [Download the equivalent Stata script for this + page](../do_files/next_steps-reshape_long_wide.do) + +# Introduction + +In this section, we show how to reshape data from long to wide (and vice +versa). We do this for both raw and cleaned data. To demonstrate, we use +data on cohort members’ height and weight collected in Sweeps 8 and 9 +(ages 25 and 32). + +The packages we use are: + +``` r +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +``` + +# Reshaping Raw Data from Wide to Long + +We begin by loading the data from each sweep and merging these together +into a single wide format data frame; see [Combining Data Across +Sweeps](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html) +for further explanation on how this is achieved. Height and weight are +stored in the main interview files for Sweeps 8 and 9 +(`ns8_2015_main_interview.dta` and `ns9_2022_main_interview.dta`, both +in the `safeguarded_eul` subfolder). The names of the height and weight +variables follow the same convention in the two sweeps, differing only +in the prefix that denotes the sweep (`W8HEIGHT` and `W9HEIGHT`; +`W8WEIGHT` and `W9WEIGHT`). This is typical for variables collected in +Sweeps 8 and 9, but [not for variables collected in both earlier and +later +sweeps](https://cls-data.github.io/docs/next_steps-data_structures.html), +which usually need to be renamed before they can be reshaped. + +``` r +df_w8 <- read_dta("safeguarded_eul/ns8_2015_main_interview.dta", + col_select = c("NSID", "W8HEIGHT", "W8WEIGHT")) + +df_w9 <- read_dta("safeguarded_eul/ns9_2022_main_interview.dta", + col_select = c("NSID", "W9HEIGHT", "W9WEIGHT")) + +df_wide <- df_w8 %>% + full_join(df_w9, by = "NSID") + +df_wide +``` + + # A tibble: 9,408 × 5 + NSID W8HEIGHT W8WEIGHT W9HEIGHT W9WEIGHT + + 1 NS10001S 1.85 73.0 NA NA + 2 NS10004W 1.55 55.3 -1 [Not applicabl… 51 + 3 NS10011M 1.73 75 -1 [Not applicabl… 89 + 4 NS10020F 1.83 -1 [Not applicable] -1 [Not applicabl… 100 + 5 NS10021G 1.85 73.5 -1 [Not applicabl… 84.8 + 6 NS10026M 1.65 62.1 -1 [Not applicabl… 73.0 + 7 NS10027N 1.7 64.0 -1 [Not applicabl… 64.0 + 8 NS10029Q -1 [Not applicable] -1 [Not applicable] 1.78 87 + 9 NS10030A 2.01 106. -1 [Not applicabl… 80 + 10 NS10031B 1.7 69.8 NA NA + # ℹ 9,398 more rows + +`df_wide` has 5 columns. Besides the identifier, `NSID`, there are 4 +columns for height and weight measurements at each sweep. Each of these +4 columns is prefixed by the letter `W` and a single digit indicating +the sweep. We can reshape the dataset into long format (one row per +person x sweep combination) using the `pivot_longer()` function so that +the resulting data frame has four columns: one person identifier, a +variable for sweep, and variables for height and weight. We specify the +columns to be reshaped using the `cols` argument, provide the new +variable names in the `names_to` argument, and the pattern the existing +column names take using the `names_pattern` argument. For +`names_pattern` we specify `"^W(\\d)(.*)$"`, which breaks the column +name into two pieces: the digit following the initial `W` (`"(\\d)"`) +and the rest of the name (`"(.*)"`). `names_pattern` uses regular +expressions.[^1] `\\d` is a special character denoting a digit, `.` +matches single characters, and `.*` modifies this to match zero or more +characters. As noted, the digit holds information on sweep; in the +reshaped data frame the digit is stored as a value in a new column +`sweep`. `.value` is a placeholder for the new columns in the reshaped +data frame that store the values from the columns selected by `cols`; +these new columns are named using the second piece from +`names_pattern` - in this case `HEIGHT` and `WEIGHT`. Finally, we use +the `names_transform` argument to convert `sweep` to an integer. As the +values of `sweep` are taken from the column names, they would otherwise +be stored as text (`"8"` and `"9"`), which is harder to work with: text +cannot be used in calculations, is sorted alphabetically rather than +numerically, and cannot be matched to a numeric sweep variable when +merging with other datasets. + +``` r +df_long <- df_wide %>% + pivot_longer(cols = matches("^W\\d(HEIGHT|WEIGHT)$"), + names_to = c("sweep", ".value"), + names_pattern = "^W(\\d)(.*)$", + names_transform = list(sweep = as.integer)) + +df_long +``` + + # A tibble: 18,816 × 4 + NSID sweep HEIGHT WEIGHT + + 1 NS10001S 8 1.85 73.0 + 2 NS10001S 9 NA NA + 3 NS10004W 8 1.55 55.3 + 4 NS10004W 9 -1 [Not applicable] 51 + 5 NS10011M 8 1.73 75 + 6 NS10011M 9 -1 [Not applicable] 89 + 7 NS10020F 8 1.83 -1 [Not applicable] + 8 NS10020F 9 -1 [Not applicable] 100 + 9 NS10021G 8 1.85 73.5 + 10 NS10021G 9 -1 [Not applicable] 84.8 + # ℹ 18,806 more rows + +Note, in the original `df_wide` tibble, the height and weight variables +were labelled numeric vectors - this class allows users to add metadata +to variables (value labels, etc.). When reshaping to long format, +multiple variables are effectively appended together, so the final +reshaped variables can only have one set of properties. `pivot_longer()` +tries to preserve variable attributes, but in some cases will throw an +error (where variables are of inconsistent types) or print a warning +(where value labels are inconsistent). This is the case here: the value +labels attached to the Sweep 8 and Sweep 9 variables are not identical, +so running the `pivot_longer()` code above produces a warning that the +variables have conflicting value labels, and the labels from the Sweep 8 +variables are used. Where this is a concern, value labels can be removed +prior to reshaping with `zap_labels()` (from `haven`). + +# Reshaping Raw Data from Long to Wide + +We can also reshape the data from long to wide format using the +`pivot_wider()` function. In this case, we want to create two new +columns for each sweep: one for height and one for weight. We specify +the columns to be reshaped using the `values_from` argument, provide the +old column names in the `names_from` argument, and use the `names_glue` +argument to specify the convention to follow for the new column names. +The `names_glue` argument uses curly braces (`{}`) to reference the +values from the `names_from` and `.value` arguments. As we are +specifying multiple columns in `values_from`, `.value` is a placeholder +for the names of the variables selected in `values_from`. + +``` r +df_long %>% + pivot_wider(names_from = sweep, + values_from = c(HEIGHT, WEIGHT), + names_glue = "W{sweep}{.value}") +``` + + # A tibble: 9,408 × 5 + NSID W8HEIGHT W9HEIGHT W8WEIGHT W9WEIGHT + + 1 NS10001S 1.85 NA 73.0 NA + 2 NS10004W 1.55 -1 [Not applicable] 55.3 51 + 3 NS10011M 1.73 -1 [Not applicable] 75 89 + 4 NS10020F 1.83 -1 [Not applicable] -1 [Not applicabl… 100 + 5 NS10021G 1.85 -1 [Not applicable] 73.5 84.8 + 6 NS10026M 1.65 -1 [Not applicable] 62.1 73.0 + 7 NS10027N 1.7 -1 [Not applicable] 64.0 64.0 + 8 NS10029Q -1 [Not applicable] 1.78 -1 [Not applicabl… 87 + 9 NS10030A 2.01 -1 [Not applicable] 106. 80 + 10 NS10031B 1.7 NA 69.8 NA + # ℹ 9,398 more rows + +# Reshaping Cleaned Data from Long to Wide + +It is likely that you will not just need to reshape raw data, but +cleaned data too. In the next two sections we offer advice on naming +variables so that they are easy to select and reshape in long or wide +formats. First, we clean the long dataset by creating a new column for +the cohort member’s age at each sweep, and creating new `height` and +`weight` variables that replace negative values in the raw height and +weight data with `NA` (as well as giving these variables more +easy-to-understand names). To create the age variable, we create a +vector, `ages`, which contains the (approximate) age of cohort members +at each of the nine sweeps, and subset it using the sweep number (i.e., +`ages[8]` returns `25`). + +``` r +ages <- c(14, 15, 16, 17, 18, 19, 20, 25, 32) + +df_long_clean <- df_long %>% + mutate(age = ages[sweep], + height = ifelse(HEIGHT > 0, HEIGHT, NA), + weight = ifelse(WEIGHT > 0, WEIGHT, NA)) %>% + select(NSID, age, height, weight) + +df_long_clean +``` + + # A tibble: 18,816 × 4 + NSID age height weight + + 1 NS10001S 25 1.85 73.0 + 2 NS10001S 32 NA NA + 3 NS10004W 25 1.55 55.3 + 4 NS10004W 32 NA 51 + 5 NS10011M 25 1.73 75 + 6 NS10011M 32 NA 89 + 7 NS10020F 25 1.83 NA + 8 NS10020F 32 NA 100 + 9 NS10021G 25 1.85 73.5 + 10 NS10021G 32 NA 84.8 + # ℹ 18,806 more rows + +To reshape the clean data from long to wide format, we can use the +`pivot_wider()` function as before. This time, we specify the column +containing the cohort member’s age in the `names_from` argument, the +columns to be reshaped in the `values_from` argument, and use the +`names_glue` argument to specify the new column names. The `names_glue` +argument uses curly braces (`{}`) to reference the values from the +`names_from` and `.value` arguments. As we are specifying multiple +columns in `values_from`, `.value` is a placeholder for the variable +name. + +``` r +df_wide_clean <- df_long_clean %>% + pivot_wider(names_from = age, + values_from = c(height, weight), + names_glue = "{.value}_{age}") + +df_wide_clean +``` + + # A tibble: 9,408 × 5 + NSID height_25 height_32 weight_25 weight_32 + + 1 NS10001S 1.85 NA 73.0 NA + 2 NS10004W 1.55 NA 55.3 51 + 3 NS10011M 1.73 NA 75 89 + 4 NS10020F 1.83 NA NA 100 + 5 NS10021G 1.85 NA 73.5 84.8 + 6 NS10026M 1.65 NA 62.1 73.0 + 7 NS10027N 1.7 NA 64.0 64.0 + 8 NS10029Q NA 1.78 NA 87 + 9 NS10030A 2.01 NA 106. 80 + 10 NS10031B 1.7 NA 69.8 NA + # ℹ 9,398 more rows + +Notice that the new variable names consist of a descriptive stem, an +underscore, and the age at measurement. A consistent convention such as +this makes it simple to subset variables either by name (e.g., +`select(matches("^height_\\d\\d$"))`) or by numerical range (e.g., +`select(matches("^(h|w)eight_2[0-9]$"))`).[^2] As cohort members were +aged between 14 and 32 in Sweeps 1-9, the age is always two characters +long. In studies that include measurements from earlier in life, it is +worth padding ages with a leading zero (e.g., `height_05`) so that the +names of similar variables are the same length. + +# Reshaping Cleaned Data from Wide to Long + +Finally, we can reshape the clean wide dataset back to long format using +the `pivot_longer()` function. We specify the columns to be reshaped +using the `cols` argument, provide the new variable names in the +`names_to` argument, and the pattern the existing column names take +using the `names_pattern` argument. For `names_pattern` we specify +`"(.*)_(\\d\\d)$"`, which breaks the column name into two pieces: the +variable name (`"(.*)"`), and the age (`"(\\d\\d)"`). As before, we use +the `names_transform` argument to convert the age to an integer. Note +how easy it is to identify the variables we want to reshape in `cols`: +because we used a consistent naming structure for the cleaned variables, +a short regular expression (`"_\\d\\d$"`) selects all of them. + +``` r +df_wide_clean %>% + pivot_longer(cols = matches("_\\d\\d$"), + names_to = c(".value", "age"), + names_pattern = "(.*)_(\\d\\d)$", + names_transform = list(age = as.integer)) +``` + + # A tibble: 18,816 × 4 + NSID age height weight + + 1 NS10001S 25 1.85 73.0 + 2 NS10001S 32 NA NA + 3 NS10004W 25 1.55 55.3 + 4 NS10004W 32 NA 51 + 5 NS10011M 25 1.73 75 + 6 NS10011M 32 NA 89 + 7 NS10020F 25 1.83 NA + 8 NS10020F 32 NA 100 + 9 NS10021G 25 1.85 73.5 + 10 NS10021G 32 NA 84.8 + # ℹ 18,806 more rows + +# Footnotes + +[^1]: Regular expressions are extremely useful and compact ways of + working with text. See [Chapter 15 in the R for Data Science + textbook](https://r4ds.hadley.nz/regexps.html) for more information. + ChatGPT and similar services are very useful for writing and + interpreting regular expressions. + +[^2]: In regular expressions, `^` and `$` are special characters that + match the beginning and end of a string, respectively. + `"^height_\\d\\d$"` matches any string that begins “height\_”, + immediately followed by two digits (0, 1, …, 9) that end the string. + `"^(h|w)eight_2[0-9]$"` matches any string that begins height or + weight, immediately followed by a number between 20 and 29 (`[0-9]` + is a compact way of matching the integer range 0, 1, …, 9). diff --git a/docs/next_steps.md b/docs/next_steps.md index 623d29a..1b276ec 100644 --- a/docs/next_steps.md +++ b/docs/next_steps.md @@ -1,15 +1,26 @@ --- layout: default title: Next Steps +has_children: true nav_order: 5 --- -This section presents code to clean and handle data from Next Steps. +This section presents code to clean and handle data from Next Steps (formerly the Longitudinal Study of Young People in England, LSYPE). Next Steps has relatively straightforward data structures: every file is linked with a single identifier, `NSID`, and most files have one row per cohort member. Difficulties mainly arise from the study's history. Next Steps was managed by the Department for Education (DfE) for its first seven sweeps and by CLS thereafter, and the naming of files and variables differs between the two eras. We provide an [introduction to the data](https://cls-data.github.io/docs/next_steps-data_structures.html) as necessary background. + +Unlike the other CLS cohorts, the End User Licence data for Next Steps are downloaded from the UK Data Service as a single study ([SN 5545](https://datacatalogue.ukdataservice.ac.uk/studies/study/5545)) that covers every sweep. The Stata (`.dta`) files are provided in three subfolders: + +- `safeguarded_eul` contains the main survey files for each sweep. +- `household_grids` contains files with information on the people the cohort member lives with. +- `activity_histories` contains files with cohort members' education and employment histories. + +There is no pressing need to reorganise the files before using them, so we do not provide code for creating a folder structure. The code in this section assumes that your working directory is the folder that contains these three subfolders (at the time of writing, `UKDA-5545-stata/stata/stata13` within the unzipped download), and refers to files using both the subfolder and file name (e.g., `safeguarded_eul/ns8_2015_derived.dta`). ## Miscellanea There are a few characteristics of Next Steps that data users should be aware of. -* Next Steps was formerly managed by the Department for Education (DfE) and, between Waves 1-7, known as the Longitudinal Study of Young People in England (LSYPE). There is a marked change in the naming of files between CLS and DfE eras. In each dataset, variable names following the rubric `WX...` where X is a number indicating wave (e.g., `W2ghq` is from the second wave). However, variable names for similar variables are not always named consistently across eras (though typically are within an era). -* Almost all datasets are at the cohort member level, withone row per-cohort member. Exception include the activity history datasets, which are at the activity level (one row per activity). -* Negative variable values are typically reserved for different forms of missingness ("Don't know", "Refuse", "Not applicable", etc.). \ No newline at end of file +- DfE documentation uses the term "wave" rather than "sweep" (hence the `W` prefix in variable names). We use "sweep" on this website. Sweeps 1-7 took place annually between 2004 and 2010 (ages 14 to 20), Sweep 8 took place in 2015/16 (age 25), and Sweep 9 in 2022/23 (age 32). +- Parents were interviewed in Sweeps 1-4. Information on a cohort member's "main parent" and "second parent" is stored in the same row (i.e., in *wide* format), in separate variables suffixed `MP` and `SP`, rather than in separate rows. The main and second parent are not necessarily the same people in each sweep. +- An ethnic minority boost sample was added to the study at Sweep 4. These cohort members have no data from Sweeps 1-3. Boost sample members can be identified with the variable `W4Boost` in `safeguarded_eul/wave_four_lsype_young_person_2020.dta` or `MAINBOOST` in `safeguarded_eul/ns9_2022_longitudinal_file.dta`. +- `safeguarded_eul/ns9_2022_longitudinal_file.dta` has one row for every cohort member and contains information on sample design, survey weights and fieldwork outcomes at each sweep. Users should consider using this dataset to define their sample. +- Negative values are typically reserved for different forms of missingness ("Don't know", "Refused", "Not applicable", etc.), but the codes used differ between the DfE and CLS eras (e.g., "Refused" is `-92` in Sweeps 1-7 but `-9` in Sweeps 8 and 9). diff --git a/images/next_steps-data_discovery.png b/images/next_steps-data_discovery.png new file mode 100644 index 0000000..176ce26 Binary files /dev/null and b/images/next_steps-data_discovery.png differ diff --git a/purl/next_steps-data_discovery.R b/purl/next_steps-data_discovery.R new file mode 100644 index 0000000..e079c26 --- /dev/null +++ b/purl/next_steps-data_discovery.R @@ -0,0 +1,51 @@ +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For searching imported datasets +library(codebookr) # For creating .docx codebooks + +ns_w8 <- read_dta("safeguarded_eul/ns8_2015_derived.dta") + +lookfor(ns_w8, "ghq") + +ns_w8_lookfor <- lookfor(ns_w8) %>% + as_tibble() %>% + mutate(variable_low = str_to_lower(variable), + label_low = str_to_lower(label)) + +ns_w8_lookfor %>% + filter(str_detect(label_low, "ghq")) + +cdb <- codebook(ns_w8) +print(cdb, "ns_w8_codebook.docx") # Saves as .docx (Word) file + +create_lookfor <- function(file_path){ + read_dta(file_path, n_max = 1) %>% + lookfor() %>% + as_tibble() +} + +folders <- c("activity_histories", "household_grids", "safeguarded_eul") + +df_lookfor <- tibble(file_path = list.files(folders, pattern = "\\.dta$", full.names = TRUE)) %>% + mutate(lookfor = map(file_path, create_lookfor)) %>% + unnest(lookfor) %>% + mutate(variable_low = str_to_lower(variable), + label_low = str_to_lower(label), + sweep = str_extract(variable_low, "^w(\\d)", group = 1) %>% + as.integer()) %>% + separate(file_path, + into = c("folder", "file"), + sep = "/", + remove = FALSE) %>% + relocate(sweep, .after = file) %>% + relocate(file_path, pos, .after = last_col()) + +df_lookfor %>% + filter(str_detect(label_low, "ghq")) %>% + select(file, sweep, variable, label) + +df_lookfor %>% + filter(str_detect(label_low, "ghq"), + str_detect(label_low, "score")) %>% + select(file, sweep, variable, label) diff --git a/purl/next_steps-data_structures.R b/purl/next_steps-data_structures.R new file mode 100644 index 0000000..6529817 --- /dev/null +++ b/purl/next_steps-data_structures.R @@ -0,0 +1,19 @@ +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For handling missing values + +negative_to_na <- function(x){ + na_range(x) <- c(-Inf, -1) + user_na_to_na(x) +} + +df_w1 <- read_dta("safeguarded_eul/wave_one_lsype_young_person_2020.dta", + col_select = c("NSID", "W1alceverYP")) + +df_w1 %>% + count(W1alceverYP) # Tabulates the raw variable + +df_w1 %>% + mutate(W1alceverYP = negative_to_na(W1alceverYP)) %>% # Replaces negative values with NA + count(W1alceverYP) # Tabulates the cleaned variable diff --git a/purl/next_steps-household_grid.R b/purl/next_steps-household_grid.R new file mode 100644 index 0000000..8cb3bf9 --- /dev/null +++ b/purl/next_steps-household_grid.R @@ -0,0 +1,85 @@ +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files + +df_w1_hhgrid <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, W1Sex, W1R_1, W1EmpStat) # Retains the listed variables + +df_w1_hhgrid %>% + count(W1Sex) # Tabulates each sex + +df_w1_hhgrid %>% + count(W1R_1) # Tabulates each relationship to the cohort member + +df_w1_mothers <- df_w1_hhgrid %>% + filter( + W1R_1 == 8, # Keep natural parents of the cohort member... + W1Sex == 2 # ...who are female. + ) %>% + add_count(NSID) %>% # Creates new variable (n) containing # of records with given NSID + filter(n == 1) %>% # Keep where only one recorded natural mother per family + select(NSID, W1HhID, W1EmpStat) # Keep identifier variables and employment status + +df_w1_mothers %>% + count(W1EmpStat) + +df_w1_mother_works <- df_w1_mothers %>% + mutate(mother_works = case_when(W1EmpStat %in% 1:2 ~ 1, # If W1EmpStat is 1 or 2, then 1 + W1EmpStat %in% 3:9 ~ 0)) %>% # If W1EmpStat is between 3 and 9, then 0 + select(NSID, mother_works) + +df_w1_mother_works %>% + count(mother_works) %>% + mutate(prop = n / sum(n)) + +df_w1_parents <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, W1Sex, W1R_1, W1mainres, W1secores) %>% + mutate(role = case_when(W1HhID == W1mainres ~ "Main parent", + W1HhID == W1secores ~ "Second parent")) %>% + drop_na(role) # Drops rows for individuals who are not the main or second parent + +df_w1_parents %>% + mutate(across(c(W1Sex, W1R_1), as_factor)) %>% + count(role, W1Sex, W1R_1) %>% + print(n = Inf) # Prints all rows + +df_w1_main <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + filter(W1HhID == W1mainres) %>% # Keeps the row for the main parent + mutate(w1_main_hhid = zap_labels(W1HhID)) %>% # Removes value labels + select(NSID, w1_main_hhid) + +df_w2_main <- read_dta("household_grids/wave_two_lsype_household_grid_file_2020.dta") %>% + filter(W2HhID == W2mainres) %>% + mutate(w2_main_hhid = zap_labels(W2HhID)) %>% + select(NSID, w2_main_hhid) + +df_main <- df_w1_main %>% + inner_join(df_w2_main, by = "NSID") + +df_main %>% + count(same_person = w1_main_hhid == w2_main_hhid) + +df_w1_hhgrid_rel <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, matches("^W1R_\\d+$")) + +df_w1_hhgrid_rel %>% + filter(NSID == first(NSID)) %>% # To look at just one household + select(W1HhID, W1R_1, W1R_2, W1R_3) # To look at first few relationship variables + +df_w1_couples <- df_w1_hhgrid_rel %>% + pivot_longer(cols = matches("^W1R_\\d+$"), + names_to = "W1HhID_alter", + names_prefix = "W1R_", # Removes "W1R_" from the names, leaving the alter's person number + names_transform = as.integer, # Converts the alter's person number to an integer + values_to = "relationship") %>% + filter(relationship %in% 1:2) %>% # Keep where husband/wife or partner/cohabitee + mutate(W1HhID = as.integer(W1HhID)) %>% # Converts the person number to an integer (removing its value labels) + select(NSID, W1HhID, partner_hhid = W1HhID_alter) + +df_w1_couples + +df_w1_couples_rev <- df_w1_couples %>% + select(NSID, W1HhID = partner_hhid, partner_hhid = W1HhID) # Swaps the person numbers of the two partners + +bind_rows(df_w1_couples, df_w1_couples_rev) %>% # Appends the two datasets + arrange(NSID, W1HhID) # Sorts the dataset by ID and person number diff --git a/purl/next_steps-merging_across_sweeps.R b/purl/next_steps-merging_across_sweeps.R new file mode 100644 index 0000000..ae62d49 --- /dev/null +++ b/purl/next_steps-merging_across_sweeps.R @@ -0,0 +1,101 @@ +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For handling missing values + +df_w2 <- read_dta("safeguarded_eul/wave_two_lsype_young_person_2020.dta", + col_select = c("NSID", "W2ghq12scr")) + +df_w4 <- read_dta("safeguarded_eul/wave_four_lsype_young_person_2020.dta", + col_select = c("NSID", "W4ghq12scr")) + +df_w2 %>% + full_join(df_w4, by = "NSID") + +df_w2 %>% + inner_join(df_w4, by = "NSID") + +df_w2 %>% + left_join(df_w4, by = "NSID") + +df_w2 %>% + right_join(df_w4, by = "NSID") + +df_w2_noprefix <- df_w2 %>% + mutate(sweep = 2, .before = 1) %>% + rename_with(~ str_remove(.x, "^W2")) + +df_w4_noprefix <- df_w4 %>% + mutate(sweep = 4, .before = 1) %>% + rename_with(~ str_remove(.x, "^W4")) + +df_w2_noprefix +df_w4_noprefix + +bind_rows(df_w2_noprefix, df_w4_noprefix) %>% + arrange(NSID, sweep) # Sorts the dataset by ID and sweep + +bind_rows(df_w2_noprefix, df_w4_noprefix) %>% + complete(NSID, sweep) %>% # Ensure cohort members have a row for each sweep + arrange(NSID, sweep) + +df_files <- tribble( + ~sweep, ~file, ~ghq_var, + 2, "safeguarded_eul/wave_two_lsype_young_person_2020.dta", "W2ghq12scr", + 4, "safeguarded_eul/wave_four_lsype_young_person_2020.dta", "W4ghq12scr", + 8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC", + 9, "safeguarded_eul/ns9_2022_derived_variables.dta", "W9DGHQSC" +) + +df_files + +load_ghq_wide <- function(sweep, file, ghq_var){ + read_dta(file, col_select = all_of(c("NSID", ghq_var))) +} + +load_ghq_wide(8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC") + +load_ghq_wide(2, "safeguarded_eul/wave_two_lsype_young_person_2020.dta", "W2ghq12scr") %>% + full_join(load_ghq_wide(4, "safeguarded_eul/wave_four_lsype_young_person_2020.dta", "W4ghq12scr"), + by = "NSID") %>% + full_join(load_ghq_wide(8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC"), + by = "NSID") %>% + full_join(load_ghq_wide(9, "safeguarded_eul/ns9_2022_derived_variables.dta", "W9DGHQSC"), + by = "NSID") + +pmap(df_files, load_ghq_wide) + +df_ghq_wide <- pmap(df_files, load_ghq_wide) %>% + reduce(~ full_join(.x, .y, by = "NSID")) + +df_ghq_wide + +load_ghq_long <- function(sweep, file, ghq_var){ + read_dta(file, col_select = all_of(c("NSID", ghq_var))) %>% + rename(ghq12 = all_of(ghq_var)) %>% + mutate(ghq12 = zap_labels(ghq12), + sweep = sweep, .before = 1) +} + +df_ghq_long <- pmap(df_files, load_ghq_long) %>% + bind_rows() %>% + arrange(NSID, sweep) # Sorts the dataset by ID and sweep + +df_ghq_long + +negative_to_na <- function(x){ + na_range(x) <- c(-Inf, -1) + user_na_to_na(x) +} + +df_ghq_long %>% + mutate(ghq12 = negative_to_na(ghq12)) # Replaces negative values with NA + +df_longitudinal <- read_dta("safeguarded_eul/ns9_2022_longitudinal_file.dta", + col_select = c("NSID", "MAINBOOST", matches("^W\\dOUTCOME$"))) + +df_longitudinal %>% + count(MAINBOOST) + +df_longitudinal %>% + left_join(df_ghq_wide, by = "NSID") diff --git a/purl/next_steps-merging_within_sweep.R b/purl/next_steps-merging_within_sweep.R new file mode 100644 index 0000000..a1d7468 --- /dev/null +++ b/purl/next_steps-merging_within_sweep.R @@ -0,0 +1,57 @@ +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files + +yp <- read_dta("safeguarded_eul/wave_one_lsype_young_person_2020.dta") # One row per cohort member +family <- read_dta("safeguarded_eul/wave_one_lsype_family_background_2020.dta") # One row per cohort member +hhgrid <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") # One row per household member + +df_yp <- yp %>% + select(NSID, sex = W1sexYP, school_attitude = W1yschat1) # Retains the listed variables, renaming W1sexYP as sex and W1yschat1 as school_attitude + +df_yp + +df_tenure <- family %>% + select(NSID, tenure = W1hous12HH) + +df_nssec <- family %>% + select(NSID, W1nssecMP, W1nssecSP) %>% + mutate(across(c(W1nssecMP, W1nssecSP), + ~ if_else(between(.x, 1, 8), as.numeric(.x), NA))) %>% # Values outside 1-8 denote various forms of missingness + mutate(family_nssec = pmin(W1nssecMP, W1nssecSP, na.rm = TRUE)) %>% # Takes the lowest value of the two variables in each row + select(NSID, family_nssec) + +df_nssec + +df_parent <- family %>% + select(NSID, W1HhIDMP = W1mainres, W1HhIDSP = W1secores, W1nssecMP, W1nssecSP) %>% + zap_labels() %>% # Removes value labels + pivot_longer(cols = -NSID, # Reshape all columns except NSID + names_to = c(".value", "parent"), + names_pattern = "^(.*)(MP|SP)$") + +df_parent + +df_mother_nssec <- hhgrid %>% + select(NSID, W1HhID, W1Sex, W1R_1) %>% + inner_join(df_parent, by = c("NSID", "W1HhID")) %>% + filter(W1R_1 == 8, # Keep natural parents... + W1Sex == 2) %>% # ...who are female + add_count(NSID) %>% # Creates new variable (n) containing # of records with given NSID + filter(n == 1) %>% # Keep where only one natural mother identified per cohort member + mutate(mother_nssec = if_else(between(W1nssec, 1, 8), W1nssec, NA)) %>% + select(NSID, mother_nssec) + +df_siblings <- hhgrid %>% + select(NSID, W1HhID, W1R_1) %>% + group_by(NSID) %>% # Groups the data so summarise() is performed per cohort member + summarise(n_siblings = sum(W1R_1 %in% 13:17), # Counts the number of rows where W1R_1 is between 13 and 17 + .groups = "drop") # Removes the grouping from the resulting dataframe + +df_siblings + +df_yp %>% + left_join(df_tenure, by = "NSID") %>% + left_join(df_nssec, by = "NSID") %>% + left_join(df_mother_nssec, by = "NSID") %>% + left_join(df_siblings, by = "NSID") diff --git a/purl/next_steps-reshape_long_wide.R b/purl/next_steps-reshape_long_wide.R new file mode 100644 index 0000000..ab40c5f --- /dev/null +++ b/purl/next_steps-reshape_long_wide.R @@ -0,0 +1,50 @@ +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files + +df_w8 <- read_dta("safeguarded_eul/ns8_2015_main_interview.dta", + col_select = c("NSID", "W8HEIGHT", "W8WEIGHT")) + +df_w9 <- read_dta("safeguarded_eul/ns9_2022_main_interview.dta", + col_select = c("NSID", "W9HEIGHT", "W9WEIGHT")) + +df_wide <- df_w8 %>% + full_join(df_w9, by = "NSID") + +df_wide + +df_long <- df_wide %>% + pivot_longer(cols = matches("^W\\d(HEIGHT|WEIGHT)$"), + names_to = c("sweep", ".value"), + names_pattern = "^W(\\d)(.*)$", + names_transform = list(sweep = as.integer)) + +df_long + +df_long %>% + pivot_wider(names_from = sweep, + values_from = c(HEIGHT, WEIGHT), + names_glue = "W{sweep}{.value}") + +ages <- c(14, 15, 16, 17, 18, 19, 20, 25, 32) + +df_long_clean <- df_long %>% + mutate(age = ages[sweep], + height = ifelse(HEIGHT > 0, HEIGHT, NA), + weight = ifelse(WEIGHT > 0, WEIGHT, NA)) %>% + select(NSID, age, height, weight) + +df_long_clean + +df_wide_clean <- df_long_clean %>% + pivot_wider(names_from = age, + values_from = c(height, weight), + names_glue = "{.value}_{age}") + +df_wide_clean + +df_wide_clean %>% + pivot_longer(cols = matches("_\\d\\d$"), + names_to = c(".value", "age"), + names_pattern = "(.*)_(\\d\\d)$", + names_transform = list(age = as.integer)) diff --git a/quarto/next_steps-data_discovery.qmd b/quarto/next_steps-data_discovery.qmd new file mode 100644 index 0000000..8bd5051 --- /dev/null +++ b/quarto/next_steps-data_discovery.qmd @@ -0,0 +1,120 @@ +--- +layout: default +title: "Data Discovery" +nav_order: 1 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + +- [Download the R script for this page](../purl/next_steps-data_discovery.R) +- [Download the equivalent Stata script for this page](../do_files/next_steps-data_discovery.do) + +# Introduction + +In this section, we show a few `R` functions for exploring Next Steps data; there's a lot of data in Next Steps, so finding a specific variable can be challenging. Variable names do not always follow a consistent convention across the whole study: Sweeps 1-7 were managed by the Department for Education and Sweeps 8-9 by CLS, and the same concept is often named differently in the two eras. (The variable for the cohort member's GHQ-12 score is `W2ghq12scr` in Sweep 2 but `W8DGHQSC` in Sweep 8, for example.) In what follows, we will use the `R` functions to find variables for cohort members' GHQ-12 (12-item General Health Questionnaire), which has been collected in several of the sweeps. + +The packages we will use are: + +```{r} +#| warning: false +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For searching imported datasets +library(codebookr) # For creating .docx codebooks +``` + +```{r} +#| include: false +# setwd(Sys.getenv("next_steps_fld")) +``` + +As a reminder, the Next Steps data files downloaded from the UK Data Service are stored across three subfolders: `safeguarded_eul`, `household_grids` and `activity_histories`. The code below assumes that your working directory is the folder that contains these three subfolders (see the [*Next Steps* landing page](https://cls-data.github.io/docs/next_steps.html)). + +# `labelled::lookfor()` + +The `labelled` package contains functionality for attaching and examining metadata in dataframes (for instance, adding labels to variables [columns]). Beyond this, it also contains the `lookfor()` function, which replicates similar functionality in `Stata`. `lookfor()` allows one to search for variables in a dataframe by keyword (regular expression); the function searches variable names as well as associated metadata (value and variable labels). It returns an object containing matching variables, their labels, and their types, etc.. Below, we read in the Next Steps Sweep 8 (age 25) dataset which contains derived variables (`safeguarded_eul/ns8_2015_derived.dta`) and use `lookfor()` to search for variables related to the `"GHQ"`. + +```{r} +ns_w8 <- read_dta("safeguarded_eul/ns8_2015_derived.dta") + +lookfor(ns_w8, "ghq") +``` + +Users may consider it easier to create a tibble of the `lookfor()` output, which can be searched and filtered using `dplyr` functions. Below, we create a `tibble` (a type of `data.frame` with good printing defaults) of the `lookfor()` output and use `filter()` to find variables with `"ghq"` in their labels. Note, we convert both the variable names and labels to lower case to make the search case insensitive. + +```{r} +ns_w8_lookfor <- lookfor(ns_w8) %>% + as_tibble() %>% + mutate(variable_low = str_to_lower(variable), + label_low = str_to_lower(label)) + +ns_w8_lookfor %>% + filter(str_detect(label_low, "ghq")) +``` + +The output shows that GHQ information in the `safeguarded_eul/ns8_2015_derived.dta` dataset is stored in the variable `W8DGHQSC`. + +# `codebookr::codebook()` + +The Next Steps datasets that are downloadable from the UK Data Service come bundled with data dictionaries within the `mrdoc` subfolder. However, these are limited in some ways. The `codebookr` package enables the creation of data dictionaries that are more customisable, and in our opinion, easy to read. Below we create a codebook for the Next Steps Sweep 8 derived variable dataset. These codebooks are intended to be saved and viewed in Microsoft Word. + +```{r} +cdb <- codebook(ns_w8) +print(cdb, "ns_w8_codebook.docx") # Saves as .docx (Word) file +``` + +A screenshot of the codebook is shown below. + +![Codebook created by codebookr::codebook()](../images/next_steps-data_discovery.png) + +# Create a Lookup Table Across All Datasets + +Creating the `lookfor()` and `codebook()` one dataset at a time does not allow one to get a quick overview of the variables available in Next Steps, including the sweeps repeatedly measured characteristics are available in. Below we create a `tibble`, `df_lookfor`, that contains `lookfor()` results for all the `.dta` files in the three Next Steps subfolders. + +To do this, we create a function, `create_lookfor()`, that takes a file path to a `.dta` file, reads in the first row of the dataset (faster than reading the full dataset), and applies `lookfor()` to it. We call this function with a `mutate()` function call to create a set of lookups for every `.dta` file we can find in the three subfolders (the argument `full.names = TRUE` means `list.files()` returns the subfolder as well as the file name; e.g., `safeguarded_eul/ns8_2015_derived.dta`). `map()` loops over every value in the `file_path` column, creating a corresponding lookup table for that file, stored as a [`list-column`](https://r4ds.hadley.nz/rectangling.html#list-columns). `unnest()` expands the results out, so rather than have one row per `file_path`, we have one row per variable. `separate()` splits the file path into two new columns, containing the subfolder and the file name. + +Unlike the other CLS cohorts, the Next Steps files are not organised into a separate folder for each sweep. However, as [variable names begin with a prefix indicating the sweep](https://cls-data.github.io/docs/next_steps-data_structures.html) (`W1`, `W2`, ..., `W9`), we can instead extract the sweep from the variable name. We do this in the second `mutate()` step below using the `str_extract()` function, which takes a regular expression: `"^w(\\d)"` matches a `w` at the start of the variable name followed by a single digit (`\\d`), and `group = 1` returns the part of the match within the parentheses (i.e., the digit). Variables that do not have a sweep prefix (for example, `NSID`) are given the value `NA`. + +```{r} +create_lookfor <- function(file_path){ + read_dta(file_path, n_max = 1) %>% + lookfor() %>% + as_tibble() +} + +folders <- c("activity_histories", "household_grids", "safeguarded_eul") + +df_lookfor <- tibble(file_path = list.files(folders, pattern = "\\.dta$", full.names = TRUE)) %>% + mutate(lookfor = map(file_path, create_lookfor)) %>% + unnest(lookfor) %>% + mutate(variable_low = str_to_lower(variable), + label_low = str_to_lower(label), + sweep = str_extract(variable_low, "^w(\\d)", group = 1) %>% + as.integer()) %>% + separate(file_path, + into = c("folder", "file"), + sep = "/", + remove = FALSE) %>% + relocate(sweep, .after = file) %>% + relocate(file_path, pos, .after = last_col()) +``` + +We can use the resulting object to search for variables with `"ghq"` in their labels. + +```{r} +df_lookfor %>% + filter(str_detect(label_low, "ghq")) %>% + select(file, sweep, variable, label) +``` + +The sweep prefix also makes it straightforward to see how the name of a variable changes over time. For instance, below we search for GHQ-12 *scores* (as opposed to the individual GHQ-12 items) by adding a second condition to `filter()`. The names follow one convention in the Sweep 2 and 4 files, and another in the Sweep 8 and 9 files. + +```{r} +df_lookfor %>% + filter(str_detect(label_low, "ghq"), + str_detect(label_low, "score")) %>% + select(file, sweep, variable, label) +``` diff --git a/quarto/next_steps-data_structures.qmd b/quarto/next_steps-data_structures.qmd new file mode 100644 index 0000000..a938437 --- /dev/null +++ b/quarto/next_steps-data_structures.qmd @@ -0,0 +1,243 @@ +--- +layout: default +title: "Data Structures" +nav_order: 2 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + +- [Download the R script for this page](../purl/next_steps-data_structures.R) +- [Download the equivalent Stata script for this page](../do_files/next_steps-data_structures.do) + +# Introduction + +Once you have downloaded the Next Steps data from the UK Data Service, you will find over fifty data files, split across three subfolders. The files differ in the sweep(s) they relate to, the part of the interview they cover, and - in some cases - the observational unit they describe. Most files contain one row per cohort member, but some contain one row per household member, one row per activity, and so on. The aim of this page is to give you an overview of the files and of the features of the study design that determine how they should be used. + +Compared with the [Millennium Cohort Study](https://cls-data.github.io/docs/mcs-data_structures.html), the data structures in Next Steps are simple. There is one cohort member per family, so a single variable, `NSID`, identifies both the cohort member and their family. `NSID` appears, with the same name, in every file. Further, where information was collected from or about a cohort member's parents, it is stored in the cohort member's row (in separate variables for each parent) rather than in separate rows. As a result, most files can be merged one-to-one using `NSID` alone. + +# Subfolders + +The data files are provided in three subfolders. Unlike the other CLS cohorts, the subfolders do not correspond to sweeps - each contains files from several sweeps. + +- `safeguarded_eul` + - Contains the main survey files for each sweep, including the cohort member and parent interviews and derived variables. Almost all of the files with one row per cohort member are found here. +- `household_grids` + - Contains files with one row for each person the cohort member lives with (see [below](#household-grid-files)). +- `activity_histories` + - Contains files with one row for each spell of education, employment or other activity reported by the cohort member. + +The code on this website assumes that your working directory is the folder that contains these three subfolders, so files are referred to by both their subfolder and file name (e.g., `safeguarded_eul/ns8_2015_derived.dta`). + +# Naming Conventions + +Next Steps was managed by the Department for Education (DfE) for Sweeps 1-7, when it was known as the Longitudinal Study of Young People in England (LSYPE), and by CLS from Sweep 8 onwards. The file names reflect this history. Files from Sweeps 1-7 begin `wave_[one-seven]` (the sweep is written as a word), while files from Sweeps 8 and 9 begin `ns8_2015` and `ns9_2022`, respectively. A small number of files combine information from several sweeps. The star (`*`) in the file names below is used as a wildcard. + +| File(s) | Subfolder | Sweeps | One row per... | Identifier(s) | +|---------|--------|--------|----------------|---------------| +| `wave_*_lsype_young_person_2020.dta` | `safeguarded_eul` | 1-7 | Cohort member | `NSID` | +| `wave_*_lsype_family_background_2020.dta` | `safeguarded_eul` | 1-5 | Cohort member | `NSID` | +| `wave_*_lsype_parental_attitudes_*.dta` | `safeguarded_eul` | 1-4 | Cohort member | `NSID` | +| `wave_*_lsype_household_grid_file_2020.dta` | `household_grids` | 1-7 | Household member | `NSID` and a person number | +| `wave_*_activity_history_file_2020.dta` | `activity_histories` | 4-7 | Activity | `NSID` and an activity number | +| `ns8_2015_main_interview.dta`, `ns8_2015_self_completion.dta`, `ns8_2015_derived.dta` | `safeguarded_eul` | 8 | Cohort member | `NSID` | +| `ns9_2022_main_interview.dta`, `ns9_2022_derived_variables.dta` | `safeguarded_eul` | 9 | Cohort member | `NSID` | +| Other `ns8_2015_*.dta` and `ns9_2022_*.dta` files | All three | 8-9 | Partnership, child, household member, etc. | `NSID` and a second identifier | +| `ns9_2022_longitudinal_file.dta` | `safeguarded_eul` | All | Cohort member | `NSID` | + +We describe each of these in more detail below. + +# Variable Names + +Variable names begin with a prefix that identifies the sweep: `W1` for Sweep 1, `W2` for Sweep 2, and so on ("W" stands for wave, the term used in DfE documentation). In Sweeps 1-7, the prefix is followed by the name of the question in the questionnaire and then, usually, a suffix that identifies who the question was asked of or relates to. The most common suffixes are: + +- `YP` - the young person (i.e., the cohort member) +- `MP` - the main parent +- `SP` - the second parent +- `HH` - the household + +For instance, `W1hiqualgMP` and `W1hiqualgSP` contain the highest qualification of the main parent and second parent, respectively, at Sweep 1. Questions where more than one answer could be given are stored as a set of binary variables, one for each answer, with a further two-character suffix (`0a`, `0b`, `0c`, ...) at the end of the variable name. + +Variable labels in Sweeps 1-7 also begin with a prefix identifying the source of the variable: `YP:`, `MP:`, `SP:`, `HH:` (household section), `HR:` (history section), `DV:` (derived variable), and `Admin:` (survey administration). Derived variables do not always carry a suffix. + +In Sweeps 8 and 9, variable names are in upper case and do not have a suffix, as only the cohort member was interviewed (e.g., `W8HEIGHT`). Derived variables begin `W8D` or `W9D` (e.g., `W8DGHQSC`). + +There are two things to be careful of. First, variables measuring the same thing are usually named consistently between sweeps within the DfE era (Sweeps 1-7) and within the CLS era (Sweeps 8-9), but not across eras. Second, the use of upper and lower case is not consistent, even for variables that are otherwise named identically (e.g., `W1alceverYP` and `W4AlcEverYP`; `W1wrk2MP` and `W1Wrk2SP`). In a few places, the sweep prefix itself is in lower case (e.g., `w3HhID` in the Sweep 3 household grid). See [*Data Discovery*](https://cls-data.github.io/docs/next_steps-data_discovery.html) for ways of finding the variables you need. + +# Young Person, Family Background and Parental Attitudes Files + +In Sweeps 1-7, the main survey data are split across up to three files (within the `safeguarded_eul` subfolder), each with one row per cohort member: + +- `wave_[one-seven]_lsype_young_person_2020.dta` + - Contains the cohort member's interview, as well as answers given by the main parent about the cohort member (e.g., on special educational needs). +- `wave_[one-five]_lsype_family_background_2020.dta` + - Contains information about the household (e.g., housing tenure) and about the cohort member's parents (e.g., their qualifications, employment and health). Parents were not interviewed after Sweep 4. At Sweep 5, limited information on parents was provided by the cohort member. +- `wave_[one-four]_lsype_parental_attitudes_*.dta` + - Contains the main parent's attitudes to the cohort member's schooling and their aspirations for the cohort member. + +As each of these files has one row per cohort member, they can be merged using `NSID` alone (see [*Combining Data Within A Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html)). Below is a schematic of the family background file, which shows how information on the main and second parent is stored in separate columns, rather than separate rows. + +| `NSID` | `W1hous12HH` | `W1hiqualgMP` | `W1hiqualgSP` | ... | +|--------|---------------|------------------------|------------------------|-----| +| NS0001 | 1 (Household) | 1 (Main parent) | 4 (Second parent) | ... | +| NS0002 | 4 (Household) | 3 (Main parent) | -98 (SP not present) | ... | +| NS0003 | 2 (Household) | 7 (Main parent) | 2 (Second parent) | ... | +| ... | ... | ... | ... | ... | + +A further file, `lsype_history_file_wave_one_and_wave_two_june_2008.dta`, contains information on the cohort member's early life (e.g., birth weight) and their family history, as reported by a parent at Sweep 1 or 2. `wave_four_lsype_history_2020.dta` contains similar information collected at Sweep 4. + +# Main and Second Parents + +In Sweeps 1-4, up to two of the cohort member's parents (or guardians) were interviewed. These are referred to as the "main parent" and the "second parent". It is important to understand that these are *roles in the interview*, not fixed individuals: + +- In Sweeps 1-3, the main parent was defined as the parent most involved in the young person's education. At Sweep 4, the main parent could be either parent - for the original sample, interviewers selected the parent they felt was more likely to take part. For the Sweep 4 boost sample, the main parent was the natural mother if available, then the natural father, then the parent most involved in the young person's education. +- At Sweep 1, the second parent was defined as another adult with a parental relationship to the young person (a natural, step, adoptive or foster parent). From Sweep 2, the second parent was defined as the partner or spouse of the main parent. +- There was no separate second parent interview at Sweep 3. Instead, the main parent answered questions on behalf of both parents. At Sweep 4, questions about the second parent were answered by the second parent if they were present and by the main parent otherwise. +- Parents were not interviewed where the young person had moved out of the parental home. + +The main and second parent roles were not carried forward from one sweep to the next. A mother may have been the main parent at Sweep 1 and the second parent at Sweep 2, for example, and the person occupying a role may also have changed because someone joined or left the household. A variable such as `W2hiqualgMP` does not, therefore, necessarily refer to the same person as `W1hiqualgMP`. + +There are two ways of working out who the main and second parent are: + +1. For many characteristics, the family background files contain derived variables that refer to the cohort member's mother and father, rather than the main and second parent (e.g., `W1hiqualgmum` and `W1hiqualgdad`). The files also contain the sex of the main and second parent (e.g., `W1sexMP` and `W1sexSP`). +2. The family background and household grid files contain variables that give the position of the main and second parent in the household grid (e.g., `W1mainres` and `W1secores` at Sweep 1). The household grid records each household member's sex and their relationship to the cohort member. As a household member is intended to keep the same position in the household grid in each sweep, these variables can also be compared across sweeps to see whether the person in a given role has changed. + +We show how to use the second of these in [*Working with the Household Grid*](https://cls-data.github.io/docs/next_steps-household_grid.html). + +Where a variable relates to a parent who was not identified or not interviewed, specific missing value codes are used: `-98` indicates that there is no such parent in the household (e.g., there is no second parent in a lone parent family) and `-99` that the parent was not interviewed. + +# Household Grid Files + +The `wave_[one-seven]_lsype_household_grid_file_2020.dta` files, which are stored in the `household_grids` subfolder, contain rosters of household members. There is one row for each individual in the household, including the cohort member. Individuals are identified by the combination of `NSID` and a person number, which is named `W1HhID`, `W2HhID`, `w3HhID`, and `W4hhid` in Sweeps 1-4 and `HHID` in Sweeps 5-7. The cohort member is always person number 1. + +| `NSID` | `W1HhID` | `W1Sex` | `W1R_1` | ... | +|--------|----------|------------|---------------------------|-----| +| NS0001 | 1 | 2 (Female) | -91 (Not applicable) | ... | +| NS0001 | 2 | 2 (Female) | 8 (Natural parent) | ... | +| NS0001 | 3 | 1 (Male) | 8 (Natural parent) | ... | +| NS0001 | 4 | 1 (Male) | 13 (Natural brother/sister) | ... | +| NS0002 | 1 | 1 (Male) | -91 (Not applicable) | ... | +| NS0002 | 2 | 2 (Female) | 8 (Natural parent) | ... | +| ... | ... | ... | ... | ... | + +In Sweeps 1-4, the household grid was typically completed by a parent and records the relationships between household members in a series of variables (`W1R_1`, `W1R_2`, and so on, at Sweep 1). The number at the end of the variable name is the person number of the other household member. Each relationship is only recorded once, in the row of the person with the higher person number (so, at Sweep 1, `W1R_2` is only filled in for household members with a person number of 3 or more), and the variables are otherwise coded as not applicable (`-91`). As the cohort member is person number 1, `W1R_1` records every other household member's relationship to the cohort member. The person numbers of the main parent and second parent are also recorded (`W1mainres` and `W1secores` at Sweep 1). In Sweeps 5-7, the household grid was completed by the cohort member and contains much less information: a single, less detailed variable (e.g., `W5RELATION`) records each person's relationship to the cohort member (at Sweep 7, this is only filled in for people who are new to the household at that sweep). + +The household grid files are described further in [*Working with the Household Grid*](https://cls-data.github.io/docs/next_steps-household_grid.html). + +# Sweep 8 and 9 Files + +From Sweep 8, only the cohort member was interviewed. For each sweep, the bulk of the data is stored in "flat" files with one row per cohort member: + +- `ns8_2015_main_interview.dta` and `ns9_2022_main_interview.dta` + - Contain the main interview. +- `ns8_2015_self_completion.dta` + - Contains the Sweep 8 self-completion questionnaire. (At Sweep 9, self-completion questions are included in the main interview file.) +- `ns8_2015_derived.dta` and `ns9_2022_derived_variables.dta` + - Contain derived variables (e.g., body mass index). + +The remaining files are "hierarchical". These store the answers to sets of questions that were repeated as many times as necessary - for instance, once for each of the cohort member's children. Each can have multiple rows per cohort member and include a second identifier that distinguishes the rows belonging to the same cohort member. Cohort members for whom the questions were not relevant (e.g., those without children) do not appear in the file at all. + +| File | One row per... | Identifiers | +|------|----------------|-------------| +| `ns8_2015_partnerships.dta` | Relationship | `NSID`, `W8RELID` | +| `ns8_2015_children.dta` | Child of the cohort member | `NSID`, `W8CHID` | +| `ns8_2015_household_members.dta` | Other household member | `NSID`, `W8HHMID` | +| `ns8_2015_activity_history.dta` | Activity | `NSID`, `W8HISTID` | +| `ns8_2015_benefits.dta` | Benefit received | `NSID`, `W8BENID` | +| `ns9_2022_partnerships.dta` | Relationship | `NSID`, `W9RELID` | +| `ns9_2022_person_grid.dta` | Partner, child or other household member | `NSID`, `GRIDID` | +| `ns9_2022_non_resident_children.dta` | Non-resident child | `NSID`, `GRIDID` | +| `ns9_2022_pregnancy_history.dta` | Child within a pregnancy | `NSID`, `W9PREGID`, `W9CHILDNO` | +| `ns9_2022_activity_history.dta` | Activity | `NSID`, `W9ACTID` | +| `ns9_2022_benefits.dta` | Benefit received | `NSID`, `W9BENID` | + +Most of these files are stored in the `safeguarded_eul` subfolder alongside the flat files. The exceptions are `ns8_2015_household_members.dta` and `ns9_2022_person_grid.dta`, which are in the `household_grids` subfolder, and the two activity history files, which are in the `activity_histories` subfolder. + +To use these files alongside the flat files, they generally need to be collapsed or reshaped so that they have one row per cohort member. We show an example of this in [*Combining Data Within A Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html). + +# Cross-Sweep Files + +A small number of files bring together information from several sweeps. These are all stored in the `safeguarded_eul` subfolder. + +- `ns9_2022_longitudinal_file.dta` + - Contains one row for every cohort member, regardless of the sweeps they took part in. It includes the sample design variables (`SAMPPSU` and `SAMPSTRATUM`), survey weights, the fieldwork outcome at each sweep (`W[1-9]OUTCOME`), and an indicator of whether the cohort member is part of the original or boost sample (`MAINBOOST`). This is a useful starting point for defining your sample. +- `lsype_main_activity_w4-7_nov2011_suppressed.dta` + - Contains one row per cohort member, with a variable for the cohort member's main activity (e.g., education or employment) in each month between September 2006 and May 2010. +- `next_steps_activities_longitudinal.dta` + - Contains one row per activity, summarising the activity histories collected in Sweeps 4-8. + +# The Sweep 4 Boost Sample + +The original Next Steps sample was drawn in 2004, when cohort members were in Year 9 at school. At Sweep 4, the study was enlarged with an ethnic minority boost sample of 352 young people from Black African and Black Caribbean backgrounds, selected from schools that did not take part in the original sampling. + +This has important consequences for how the data are used: + +- Boost sample members have no data for Sweeps 1-3. This is not a result of non-response. Some background information that was collected from the original sample in Sweeps 1-3 was instead collected from the boost sample at Sweep 4, so the Sweep 4 files contain variables that were only asked of boost sample members. +- Analyses that use data from Sweeps 1-3 are necessarily restricted to the original sample, and different survey weights are provided for analyses that include and exclude the boost sample (e.g., `W4WEIGHT_MAIN_BOOST` and `W4WEIGHT_MAIN` in `ns9_2022_longitudinal_file.dta`). + +Boost sample members can be identified in two ways: + +- `W4Boost` in `wave_four_lsype_young_person_2020.dta` (`1 [Yes]` or `2 [No]`). This variable is also available in the other Sweep 4 files. +- `MAINBOOST` in `ns9_2022_longitudinal_file.dta` (`1 [Main]` or `2 [Boost]`). As this file contains every cohort member, `MAINBOOST` is available for individuals who did not take part in Sweep 4. + +# Missing Values + +Negative values are used to indicate different forms of missing data. The values used differ between the DfE and CLS eras. The most common are shown below, though individual variables may use other codes. It is always worth checking the value labels of a variable before using it. + +| Sweeps 1-7 | | Sweeps 8-9 | | +|------------|----------------------------------------------|------------|------------------------| +| `-1` | Don't know | `-1` | Not applicable | +| `-91` | Not applicable | `-3` | Not asked | +| `-92` | Refused | `-8` | Don't know or insufficient information | +| `-94` | Insufficient information | `-9` | Refused | +| `-96` | Unable to complete self-completion section | | | +| `-97` | Refused self-completion section | | | +| `-98` | Parent not present in household | | | +| `-99` | Respondent not interviewed | | | +| `-996` | No parent in household | | | +| `-997` | Script error | | | +| `-998` | Interviewer missed question | | | +| `-999` | Missing household data | | | + +Note in particular that `-1` means "Don't know" in Sweeps 1-7 but "Not applicable" in Sweeps 8 and 9. + +`R` does not know that these values denote missing data. Unless they are dealt with, negative values are treated as valid values: a mean or a regression model would include values such as `-92`, for instance, and each type of missingness would appear as a category of its own in a tabulation. Negative values therefore usually need to be converted to `R`'s missing value, `NA`, before a variable is used in an analysis. Below, we show one way of doing this, using the following packages: + +```{r} +#| warning: false +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For handling missing values +``` + +```{r} +#| include: false +# setwd(Sys.getenv("next_steps_fld")) +``` + +We create a short function, `negative_to_na()`, which uses two functions from the `labelled` package: `na_range()` declares that all values between negative infinity (`-Inf`) and `-1` denote missing data, and `user_na_to_na()` converts the values that have been declared as missing to `NA`. + +```{r} +negative_to_na <- function(x){ + na_range(x) <- c(-Inf, -1) + user_na_to_na(x) +} +``` + +To show the function in action, we load the variable `W1alceverYP` (whether the cohort member has ever had a proper alcoholic drink) from the Sweep 1 young person file, and use `count()` to tabulate the variable before and after applying `negative_to_na()`. + +```{r} +df_w1 <- read_dta("safeguarded_eul/wave_one_lsype_young_person_2020.dta", + col_select = c("NSID", "W1alceverYP")) + +df_w1 %>% + count(W1alceverYP) # Tabulates the raw variable + +df_w1 %>% + mutate(W1alceverYP = negative_to_na(W1alceverYP)) %>% # Replaces negative values with NA + count(W1alceverYP) # Tabulates the cleaned variable +``` + +In the second table, the negative values have been replaced with `NA`. Note, `negative_to_na()` treats *every* negative value as missing, so it should not be used with variables that can take genuinely negative values. diff --git a/quarto/next_steps-household_grid.qmd b/quarto/next_steps-household_grid.qmd new file mode 100644 index 0000000..0f33f9b --- /dev/null +++ b/quarto/next_steps-household_grid.qmd @@ -0,0 +1,195 @@ +--- +layout: default +title: "Working with the Household Grid" +nav_order: 3 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + +- [Download the R script for this page](../purl/next_steps-household_grid.R) +- [Download the equivalent Stata script for this page](../do_files/next_steps-household_grid.do) + +# Introduction + +In this section, we describe the basics of using the household grid. Specifically, we show how to use the household grid to: + +1. Identify particular family members + +2. Create family-member specific variables + +3. Find out who the "main parent" and "second parent" are, and whether these are the same people in each sweep + +4. Determine the relationships between other members of the household. + +We use the following packages: + +```{r} +#| warning: false +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +``` + +```{r} +#| include: false +# setwd(Sys.getenv("next_steps_fld")) +``` + +# Finding Mother of Cohort Members + +To show how to perform 1 & 2, we use the example of finding natural mothers' employment status at the first sweep. The household grids are stored in their own subfolder, `household_grids`. The Sweep 1 household grid (`household_grids/wave_one_lsype_household_grid_file_2020.dta`) has one row for each member of the cohort member's household, [including the cohort member themselves](https://cls-data.github.io/docs/next_steps-data_structures.html). We load just five variables: `NSID` and `W1HhID`, which together uniquely identify an individual, `W1Sex` and `W1R_1`, which contain information on the individual's sex and their relationship to the cohort member, and `W1EmpStat`, which contains their employment status. + +`W1HhID` is the individual's person number within the household. The cohort member is always person number 1. The household grid records the relationships between household members in the variables `W1R_1`, `W1R_2`, ..., `W1R_14`; the number at the end of the variable name is the person number of the *other* household member. `W1R_1` therefore records the relationship of the person in the row to person number 1 - that is, to the cohort member. + +`W1R_1 == 8` identifies natural parents and `W1Sex == 2` identifies females. Combining the two identifies natural mothers. Below, we use `count()` to show the different (observed) values for the sex and relationship variables. We also use the `filter()` function (which retains observations where the conditions are `TRUE`) to create a dataset containing natural mothers only. `add_count(NSID) %>% filter(n == 1)` is included as an interim step to ensure there is just one natural mother per family.[^1] + +[^1]: Loading the `.dta` files into `R` with `haven::read_dta()` retains the dataset metadata, including variable names and labels, mainly by storing variables as `labelled` class objects. See the [`labelled` package help files](https://cran.r-project.org/web/packages/labelled/vignettes/intro_labelled.html) for more information on working with this metadata - for instance, converting `labelled` variables to standard `R` factor variables or replacing negative values (generally reserved in Next Steps data to indicate missingness) with `R`'s native `NA` value. + +```{r} +df_w1_hhgrid <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, W1Sex, W1R_1, W1EmpStat) # Retains the listed variables + +df_w1_hhgrid %>% + count(W1Sex) # Tabulates each sex + +df_w1_hhgrid %>% + count(W1R_1) # Tabulates each relationship to the cohort member + +df_w1_mothers <- df_w1_hhgrid %>% + filter( + W1R_1 == 8, # Keep natural parents of the cohort member... + W1Sex == 2 # ...who are female. + ) %>% + add_count(NSID) %>% # Creates new variable (n) containing # of records with given NSID + filter(n == 1) %>% # Keep where only one recorded natural mother per family + select(NSID, W1HhID, W1EmpStat) # Keep identifier variables and employment status +``` + +Note, there is one cohort member per family in Next Steps. There is, therefore, no ambiguity about which cohort member a relationship refers to. + +# Creating a Mother's Employment Variable + +Unlike in the [Millennium Cohort Study](https://cls-data.github.io/docs/mcs-household_grid.html), the Next Steps household grid holds several characteristics of each household member, including their employment status (`W1EmpStat`), marital status (`W1MarStat`) and ethnic group (`W1EthGrp`). Having identified natural mothers, we can therefore create a variable for whether the cohort member's mother is in paid work directly. `W1EmpStat` takes the values `1` and `2` for individuals in full-time and part-time paid work, respectively, and values between `3` and `9` for other statuses (e.g., looking after the family or household). Below, we use `case_when()` to create a binary variable, `mother_works`, and use `count()` to tabulate the number and proportion of mothers who are and are not in paid work. + +```{r} +df_w1_mothers %>% + count(W1EmpStat) + +df_w1_mother_works <- df_w1_mothers %>% + mutate(mother_works = case_when(W1EmpStat %in% 1:2 ~ 1, # If W1EmpStat is 1 or 2, then 1 + W1EmpStat %in% 3:9 ~ 0)) %>% # If W1EmpStat is between 3 and 9, then 0 + select(NSID, mother_works) + +df_w1_mother_works %>% + count(mother_works) %>% + mutate(prop = n / sum(n)) +``` + +The result is a dataset with one row per family with an identified natural mother, which can be merged with other cohort member-level datasets using `NSID`. Note, the family background files contain derived variables for some characteristics of the cohort member's mother and father (in this case, `W1empsmum` and `W1empsdad` in `safeguarded_eul/wave_one_lsype_family_background_2020.dta`). The approach shown here is needed where a derived variable is not available, or where you are interested in other family members, such as siblings or grandparents. + +# Identifying the Main and Second Parent + +In Sweeps 1-4, [interviews were conducted with a "main parent" and a "second parent"](https://cls-data.github.io/docs/next_steps-data_structures.html). Variables relating to these individuals are suffixed `MP` and `SP` (for example, `W1hiqualgMP` and `W1hiqualgSP` in `safeguarded_eul/wave_one_lsype_family_background_2020.dta`). To interpret these variables, it is helpful to know who the main and second parent are. + +The household grid contains the variables `W1mainres` and `W1secores`, which record the person numbers of the main parent and second parent, respectively. These variables take the same value for every member of a household. Below, we create a variable, `role`, by comparing each individual's person number (`W1HhID`) to these variables, and keep the rows for individuals who are either the main or second parent. We then tabulate the sex of main and second parents and their relationship to the cohort member. `as_factor()` (from `haven`) converts the `labelled` variables to factors so that value labels, rather than numeric values, are displayed. + +```{r} +df_w1_parents <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, W1Sex, W1R_1, W1mainres, W1secores) %>% + mutate(role = case_when(W1HhID == W1mainres ~ "Main parent", + W1HhID == W1secores ~ "Second parent")) %>% + drop_na(role) # Drops rows for individuals who are not the main or second parent + +df_w1_parents %>% + mutate(across(c(W1Sex, W1R_1), as_factor)) %>% + count(role, W1Sex, W1R_1) %>% + print(n = Inf) # Prints all rows +``` + +`df_w1_parents` has one row per parent. It can be used to create variables for a specific type of parent from the `MP` and `SP` variables. We show an example of this in [*Combining Data Within A Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html). + +## Changes in the Main and Second Parent Across Sweeps + +The main and second parent are roles in the interview rather than fixed individuals: the person interviewed as the main parent in one sweep is not necessarily the person interviewed as the main parent in the next. This matters when using `MP` and `SP` variables from more than one sweep. + +A household member is intended to keep the same person number in each sweep, so we can check whether the main parent has changed by comparing the person number of the main parent across sweeps. Below, we do this for Sweeps 1 and 2. For each sweep, we create a dataset containing the row for the main parent from that sweep's household grid, keeping their person number. (The Sweep 2 household grid, `household_grids/wave_two_lsype_household_grid_file_2020.dta`, contains equivalent variables to the Sweep 1 grid, with the prefix `W2` rather than `W1`.) We use `zap_labels()` (from `haven`) to remove the value labels from the person numbers, leaving standard numeric variables that can be compared directly. + +```{r} +df_w1_main <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + filter(W1HhID == W1mainres) %>% # Keeps the row for the main parent + mutate(w1_main_hhid = zap_labels(W1HhID)) %>% # Removes value labels + select(NSID, w1_main_hhid) + +df_w2_main <- read_dta("household_grids/wave_two_lsype_household_grid_file_2020.dta") %>% + filter(W2HhID == W2mainres) %>% + mutate(w2_main_hhid = zap_labels(W2HhID)) %>% + select(NSID, w2_main_hhid) +``` + +We then merge the two datasets using `inner_join()`, so that we keep the families where a main parent was identified in both sweeps, and tabulate whether the main parent has the same person number in the two sweeps. + +```{r} +df_main <- df_w1_main %>% + inner_join(df_w2_main, by = "NSID") + +df_main %>% + count(same_person = w1_main_hhid == w2_main_hhid) +``` + +Where the main parent is not the same person in the two sweeps, a variable such as `W2hiqualgMP` describes a different person to `W1hiqualgMP`. Where this matters for your analysis, you could restrict the sample to families where the main parent is unchanged, or use the approach shown above to create variables for a particular parent (e.g., the mother) in each sweep. + +# Determining Relationships between Other Household Members + +So far we have only used `W1R_1`, the relationship of each household member to the cohort member. The remaining relationship variables (`W1R_2` to `W1R_14`) can be used to identify the relationships between other members of the household. Specifically, they record the person in the row's (ego) relationship to the person denoted by the column (alter); the number at the end of the variable name corresponds to the alter's `W1HhID`. For instance, the variable `W1R_2` denotes the relationship of the person in the row to the person in the same household with `W1HhID == 2`. Below, we extract a small set of data from the Sweep 1 household grid to show this in action. + +```{r} +df_w1_hhgrid_rel <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") %>% + select(NSID, W1HhID, matches("^W1R_\\d+$")) + +df_w1_hhgrid_rel %>% + filter(NSID == first(NSID)) %>% # To look at just one household + select(W1HhID, W1R_1, W1R_2, W1R_3) # To look at first few relationship variables +``` + +Each row shows the relationships of one household member to the first three people in the household. For instance, where the person with `W1HhID == 2` is the natural parent of the cohort member, their row has `W1R_1 == 8 [Natural parent]`. Note, each relationship is only recorded once, in the row of the person with the *higher* person number: a relationship variable is only filled in where the individual's `W1HhID` is greater than the number at the end of the variable name, and is otherwise coded as not applicable (`-91`). `W1R_2`, for instance, is only filled in for individuals with a `W1HhID` of 3 or more, and every relationship variable is coded as not applicable for the cohort member (`W1HhID == 1`). The relationship in the other direction is not recorded and has to be inferred - if the person with `W1HhID == 2` is the natural parent of the cohort member, then the cohort member is the natural child of that person. + +If we want to find the particular person occupying a specific relationship for an individual (e.g., we want to know the `W1HhID` of the person's partner), we need to reshape the data into long-format with one row per ego-alter relationship within a household (for more on reshaping data, see [*Reshaping Data from Long to Wide (or Wide to Long)*](https://cls-data.github.io/docs/next_steps-reshape_long_wide.html)). For instance, to find the individuals who are spouses or partners, we can do the following: + +```{r} +#| warning: false +df_w1_couples <- df_w1_hhgrid_rel %>% + pivot_longer(cols = matches("^W1R_\\d+$"), + names_to = "W1HhID_alter", + names_prefix = "W1R_", # Removes "W1R_" from the names, leaving the alter's person number + names_transform = as.integer, # Converts the alter's person number to an integer + values_to = "relationship") %>% + filter(relationship %in% 1:2) %>% # Keep where husband/wife or partner/cohabitee + mutate(W1HhID = as.integer(W1HhID)) %>% # Converts the person number to an integer (removing its value labels) + select(NSID, W1HhID, partner_hhid = W1HhID_alter) + +df_w1_couples +``` + +As each relationship is only recorded once, `df_w1_couples` has one row per *couple*, with the partner with the higher person number in the `W1HhID` column. To find each person's spouse or partner (conditional on one being present), both members of a couple need a row. Below, we create a copy of the dataset in which the person numbers of the two partners are swapped, and append this to the original using `bind_rows()`. Swapping the person numbers is sufficient here as the relationship is the same in both directions; for other relationships (e.g., parent and child), the relationship itself would also need to be recoded. + +```{r} +df_w1_couples_rev <- df_w1_couples %>% + select(NSID, W1HhID = partner_hhid, partner_hhid = W1HhID) # Swaps the person numbers of the two partners + +bind_rows(df_w1_couples, df_w1_couples_rev) %>% # Appends the two datasets + arrange(NSID, W1HhID) # Sorts the dataset by ID and person number +``` + +# Coda + +This only scratches the surface of what can be achieved with the household grid. A few further points are worth noting: + +- The household grids for Sweeps 2-4 (`wave_[two-four]_lsype_household_grid_file_2020.dta`) have a similar structure to the Sweep 1 grid. The relationship variables (`W2R_1`, `w3R_1`, `W4R_1`, and so on) follow the same rule: each relationship is only recorded once, in the row of the person with the higher person number. Variable names differ in their use of upper and lower case, however: for instance, the person number is `W2HhID` in Sweep 2, `w3HhID` in Sweep 3 and `W4hhid` in Sweep 4.[^2] These grids also include people who have left the household since an earlier sweep; the variables `W2SHGInt`, `w3SHGint` and `W4SHGint` record whether a person is still living with the cohort member. +- From Sweep 5, the household grid was completed by the cohort member and is much less detailed. The Sweep 5-7 grids (`wave_[five-seven]_lsype_household_grid_file_2020.dta`) contain a single variable recording a simplified relationship to the cohort member (e.g., `W5RELATION`), and the main and second parent are no longer identified. The person number is named `HHID` in these files. Note, at Sweep 7, `W7RELATION` is only filled in for people who are new to the household at that sweep (`W7SHGINT == 2 [Present - New at current wave]`) and is coded `-91 [Not applicable]` for everyone else; at Sweeps 5 and 6, the relationship is recorded for all people present in the household (this is not documented in the user guide). For people who were already in the household at Sweep 7, the relationship to the cohort member therefore needs to be taken from the Sweep 5 or 6 grid, by matching on `NSID` and `HHID`. +- At Sweeps 8 and 9, information on the people the cohort member lives with is contained in `ns8_2015_household_members.dta` and `ns9_2022_person_grid.dta` (both also in the `household_grids` subfolder). These files do not include a row for the cohort member, and the relationship to the cohort member is recorded in the variables `W8RELTOKEY` and `W9RELTOKEY`, respectively. + +[^2]: `rename_with()` can be used to rename variables *en masse* so that they follow the same rubric. For instance, `rename_with(str_to_upper)` converts every variable name in a dataset to upper case, so that the person number would be named `W2HHID`, `W3HHID` and `W4HHID` in Sweeps 2, 3 and 4, respectively. See [*Combining Data Across Sweeps*](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html) for more on `rename_with()`. + +# Footnotes diff --git a/quarto/next_steps-merging_across_sweeps.qmd b/quarto/next_steps-merging_across_sweeps.qmd new file mode 100644 index 0000000..ab0e990 --- /dev/null +++ b/quarto/next_steps-merging_across_sweeps.qmd @@ -0,0 +1,231 @@ +--- +layout: default +title: "Combining Data Across Sweeps" +nav_order: 4 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + +- [Download the R script for this page](../purl/next_steps-merging_across_sweeps.R) +- [Download the equivalent Stata script for this page](../do_files/next_steps-merging_across_sweeps.do) + +# Introduction + +In this section, we show how to combine Next Steps data across sweeps, assuming the data to be merged have one row per cohort member; for information on restructuring data that are not in this format see the page [*Combining Data Within A Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html). + +As an example, we use data on cohort members' GHQ-12 scores (a measure of psychological distress), which were recorded in Sweeps 2, 4, 8 and 9 (ages 15, 17, 25 and 32). The scores are available in the Sweep 2 and 4 young person files (`wave_two_lsype_young_person_2020.dta` and `wave_four_lsype_young_person_2020.dta`) and the Sweep 8 and 9 derived variable files (`ns8_2015_derived.dta` and `ns9_2022_derived_variables.dta`). These files contain one row per cohort member. All four are stored in the `safeguarded_eul` subfolder. + +We begin by combining data from the second and fourth sweeps, showing how to combine these datasets in **wide** (one row per observational unit) and **long** (multiple rows per observational unit) formats by *merging* and *appending*, respectively. We then show how to combine data from multiple sweeps *programmatically* using the `dplyr` and `purrr` packages (from the `tidyverse`). This requires a little more preparation than in, e.g., the [MCS](https://cls-data.github.io/docs/mcs-merging_across_sweeps.html), as the names of files and variables do not follow a single convention across the whole study. + +We use the following packages: + +```{r} +#| warning: false +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +library(labelled) # For handling missing values +``` + +```{r} +#| include: false +# setwd(Sys.getenv("next_steps_fld")) +``` + +# Merging Across Sweeps + +The variables `W2ghq12scr` and `W4ghq12scr` contain the cohort member's GHQ-12 score at Sweep 2 and Sweep 4, respectively. [Variable names in Next Steps begin with a prefix denoting the sweep](https://cls-data.github.io/docs/next_steps-data_structures.html) (`W2`, `W4`), and in this case the rest of the name is the same in the two sweeps. Cohort members are identified with a single variable, `NSID`, which has the same name in every file. We will use the `read_dta()` function from `haven` to read in the data from the second and fourth sweeps, specifying the `col_select` argument to keep only the variables we need (the identifier and GHQ-12 score). + +```{r} +df_w2 <- read_dta("safeguarded_eul/wave_two_lsype_young_person_2020.dta", + col_select = c("NSID", "W2ghq12scr")) + +df_w4 <- read_dta("safeguarded_eul/wave_four_lsype_young_person_2020.dta", + col_select = c("NSID", "W4ghq12scr")) +``` + +We can merge these datasets by row using the `*_join()` family of functions. These share a common syntax. They take two data frames (`x` and `y`) as arguments, as well as a `by` argument that specifies the variable(s) to join on. The `*_join()` functions are: + +1. `full_join(x, y)`: Returns all rows from `x` and `y`, and all columns from `x` and `y`. For rows without matches in both `x` and `y`, the missing value `NA` is used for columns that are not used as identifiers. +2. `inner_join(x, y)`: Returns all rows from `x` and `y` where there are matching rows in both data frames. +3. `left_join(x, y)`: Returns all rows from `x`, and all columns from `x` and `y`. Rows in `x` with no match in `y` will have `NA` values in the new columns from `y`. +4. `right_join(x, y)`: Returns all rows from `y`, and all columns from `x` and `y`. Rows in `y` with no match in `x` will have `NA` values in the columns of `x`. + +In the current context, where `x` is data from the second sweep (`df_w2`) and `y` is data from the fourth sweep (`df_w4`), and these datasets only contain rows for *respondents*: `full_join()` will return a row for each individual present in the second or fourth sweeps, with the GHQ-12 score from each sweep in the same row; `inner_join()` will return a row for each individual who was present in both sweeps, with the GHQ-12 score from each sweep in the same row; `left_join()` will return a row for each individual in the second sweep, with the GHQ-12 score from the fourth sweep in the same row if the individual was present in the fourth sweep; `right_join()` will return a row for each individual in the fourth sweep, with the GHQ-12 score from the second sweep in the same row if the individual was present in the second sweep. + +To specify the identifier, we pass its name to the `by` argument. The `*_join()` functions can also handle multiple variables to join on, as well as situations where the identifiers have different names across `x` and `y`, but neither is necessary here. + +```{r} +df_w2 %>% + full_join(df_w4, by = "NSID") + +df_w2 %>% + inner_join(df_w4, by = "NSID") + +df_w2 %>% + left_join(df_w4, by = "NSID") + +df_w2 %>% + right_join(df_w4, by = "NSID") +``` + +Note, the `*_join()` functions will merge any matching rows. Unlike `Stata`, we do not have to explicitly state whether we want a 1-to-1, many-to-1, 1-to-many, or many-to-many merge. This is determined by the data that are inputted to `*_join()`. `R` will not throw an error if matches are not 1-to-1 (though it does throw a warning where matches are many-to-many), so care must be taken, for instance, when merging files with different structures. See [*Combining Data Within A Sweep*](https://cls-data.github.io/docs/next_steps-merging_within_sweep.html) for more information. + +# Appending Sweeps + +To put the data into long format, we can use the `bind_rows()` function. (In this case, the data will have one row per cohort-member x sweep combination.) To work properly, we need to name the variables consistently across sweeps, which here means removing the sweep-specific prefixes (e.g., the `W2` from `W2ghq12scr` in `df_w2`). We also need to add a variable to identify the sweep the data comes from. Below, we use the `mutate()` function to create a `sweep` variable and then use the `rename_with()` function to remove the prefixes and rename the variables consistently across sweeps. + +```{r} +df_w2_noprefix <- df_w2 %>% + mutate(sweep = 2, .before = 1) %>% + rename_with(~ str_remove(.x, "^W2")) + +df_w4_noprefix <- df_w4 %>% + mutate(sweep = 4, .before = 1) %>% + rename_with(~ str_remove(.x, "^W4")) +``` + +`rename_with()` applies a function to the names of the variables. In this case, we use the `str_remove()` function from the `stringr` package (part of the `tidyverse`) to remove the prefix from the variable names. The `~` symbol is used to create an [*anonymous function*](https://r4ds.hadley.nz/iteration.html), which is applied to each variable name. The `.x` symbol in the anonymous function is a placeholder for the variable name. `str_remove()` takes a regular expression. The `^` symbol is used to match the start of the string (so `^W2` removes `W2` where these are the first characters in a variable name). Note, for the `mutate()` call, the `.before` argument is used to specify the position of the new variable in the data frame - here we specify `sweep` as the first column. Below we see what the formatted data frames look like: + +```{r} +df_w2_noprefix +df_w4_noprefix +``` + +Now the data have been prepared, we can use `bind_rows()` to append the data frames together. This will stack the data frames on top of each other, so the number of rows is equal to the sum of rows in the individual datasets. The `bind_rows()` function can handle data frames with different numbers of columns. Missing columns are filled with `NA` values. + +```{r} +bind_rows(df_w2_noprefix, df_w4_noprefix) %>% + arrange(NSID, sweep) # Sorts the dataset by ID and sweep +``` + +Notice that with `bind_rows()` a cohort member has only as many rows of data as the times they appeared in Sweeps 2 and 4. This differs from `*_join()` where an explicit missing `NA` value is generated for the missing sweep. The `tidyverse` function `complete()` [can be used to create missing rows](https://r4ds.hadley.nz/missing-values.html#sec-missing-implicit), which can be useful if you need to generate a balanced panel of observations from which to begin analysis with (e.g., when performing multiple imputation in long format). + +```{r} +bind_rows(df_w2_noprefix, df_w4_noprefix) %>% + complete(NSID, sweep) %>% # Ensure cohort members have a row for each sweep + arrange(NSID, sweep) +``` + +Note, `rename_with()` can also be used to ensure that variables use the same case in each sweep - for instance, `rename_with(str_to_upper)` converts every variable name in a dataset to upper case. This is useful in Next Steps as the use of upper and lower case in variable names sometimes varies in hard-to-predict ways across sweeps (e.g., `W1alceverYP` and `W4AlcEverYP`). + +# Combining Sweeps Programmatically + +Combining sweeps manually can become tedious when more than two sweeps need to be combined. Instead, [iterative programming](https://r4ds.hadley.nz/iteration) can be used to automate the process. Below we show how to merge and append multiple sweeps together with very little code using the `purrr` package (part of the `tidyverse`). + +In some studies, file and variable names follow a formula, so the name of the file and variable for a given sweep can be constructed from the sweep number. This is not the case in Next Steps. The sweep is written as a word in the names of files from Sweeps 1-7 (`wave_two_...`) and as a number in the names of files from Sweeps 8 and 9 (`ns8_...`), and the GHQ-12 score is named `W2ghq12scr` and `W4ghq12scr` in Sweeps 2 and 4 but `W8DGHQSC` and `W9DGHQSC` in Sweeps 8 and 9. A simple way of handling this is to create a lookup table that lists the file and variable to use for each sweep. Below, we create one using the `tribble()` function, which allows a `tibble` to be written out row-by-row. Note, the `file` column includes the subfolder in which each file is stored. (See [*Data Discovery*](https://cls-data.github.io/docs/next_steps-data_discovery.html) for ways of finding the names of the files and variables you need.) + +```{r} +df_files <- tribble( + ~sweep, ~file, ~ghq_var, + 2, "safeguarded_eul/wave_two_lsype_young_person_2020.dta", "W2ghq12scr", + 4, "safeguarded_eul/wave_four_lsype_young_person_2020.dta", "W4ghq12scr", + 8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC", + 9, "safeguarded_eul/ns9_2022_derived_variables.dta", "W9DGHQSC" +) + +df_files +``` + +## Merging Programmatically + +Before merging the datasets together, we need to load the data for each sweep. We can do this by creating a function, `load_ghq_wide()`, which takes three arguments - `sweep`, `file`, and `ghq_var` - corresponding to the columns of `df_files`, and loads the GHQ-12 data from the specified file. The `col_select` argument is again used to keep only the variables we need. As the name of the GHQ-12 variable is stored in an object (`ghq_var`), we wrap the names in `all_of()`, which tells `read_dta()` to select the variables whose names are stored in the vector. + +```{r} +load_ghq_wide <- function(sweep, file, ghq_var){ + read_dta(file, col_select = all_of(c("NSID", ghq_var))) +} +``` + +To confirm the function is working correctly, below we call it to load data from the eighth sweep. + +```{r} +load_ghq_wide(8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC") +``` + +We could manually load and merge successively using multiple `load_ghq_wide()` and `full_join()` function calls. However, this is rather verbose: + +```{r} +load_ghq_wide(2, "safeguarded_eul/wave_two_lsype_young_person_2020.dta", "W2ghq12scr") %>% + full_join(load_ghq_wide(4, "safeguarded_eul/wave_four_lsype_young_person_2020.dta", "W4ghq12scr"), + by = "NSID") %>% + full_join(load_ghq_wide(8, "safeguarded_eul/ns8_2015_derived.dta", "W8DGHQSC"), + by = "NSID") %>% + full_join(load_ghq_wide(9, "safeguarded_eul/ns9_2022_derived_variables.dta", "W9DGHQSC"), + by = "NSID") +``` + +More efficiently, we can use the `pmap()` function from the `purrr` package (part of the `tidyverse`) to apply the `load_ghq_wide()` function to each row of `df_files` in turn. `pmap()` takes a data frame (or list) as its first argument and a function to apply as its second argument. It calls the function once per row of the data frame, matching the columns of the data frame to the arguments of the function by name (which is why the arguments of `load_ghq_wide()` have the same names as the columns of `df_files`). `pmap()` returns the results as a `list`. Below we use `pmap()` to run `load_ghq_wide()` for Sweeps 2, 4, 8 and 9. To save space, we do not print the output. + +```{r} +#| output: false +pmap(df_files, load_ghq_wide) +``` + +To merge the list of datasets returned by `pmap()` together, we can use the `reduce()` function from `purrr`. `reduce()` takes an object as its first argument, and a function as its second argument. It applies the function to the first *two* elements of the object placed into the first argument, and then successively applies the function to the result and the third element of the list onwards, until the list is finished. Below, we use `reduce()` to apply the `full_join()` function to the list of data frames. We specify `full_join()` in an anonymous function. `.x` and `.y` are the first and second inputs, respectively. In this case, at the first iteration Sweep 2 (`.x`) is merged with Sweep 4 (`.y`), and at the second iteration, the result of the first iteration (`.x`) is merged with Sweep 8 (`.y`). This process is repeated until Sweep 9 has been merged in. + +```{r} +df_ghq_wide <- pmap(df_files, load_ghq_wide) %>% + reduce(~ full_join(.x, .y, by = "NSID")) + +df_ghq_wide +``` + +## Appending Programmatically + +To append the datasets together, we create a second function, `load_ghq_long()`, to load the GHQ-12 data from a given sweep and format it so that it can be appended to the other sweeps (i.e., giving variables consistent names). As the GHQ-12 variable is not named consistently across sweeps, removing the sweep prefix is not sufficient here. Instead, we use `rename()` to give the variable a new name, `ghq12`. We also add a variable identifying the sweep. Note, the GHQ-12 scores are stored as `labelled` variables, with value labels attached to the negative values that indicate different types of missing data. The value labels (and the values used for missing data) differ between the DfE and CLS eras, so we use `zap_labels()` (from `haven`) to remove the labels, leaving a standard numeric variable. + +```{r} +load_ghq_long <- function(sweep, file, ghq_var){ + read_dta(file, col_select = all_of(c("NSID", ghq_var))) %>% + rename(ghq12 = all_of(ghq_var)) %>% + mutate(ghq12 = zap_labels(ghq12), + sweep = sweep, .before = 1) +} +``` + +To load data from Sweeps 2, 4, 8 and 9 and append them together, we can again use `pmap()` and pass the result to `bind_rows()`, which can take a list of data frames as its input. As before, we use `arrange()` to sort the dataset by ID and sweep. + +```{r} +df_ghq_long <- pmap(df_files, load_ghq_long) %>% + bind_rows() %>% + arrange(NSID, sweep) # Sorts the dataset by ID and sweep + +df_ghq_long +``` + +Before using these data, the negative values would need to be replaced with missing values (`NA`). Below, we do this with the `negative_to_na()` function introduced in [*Data Structures*](https://cls-data.github.io/docs/next_steps-data_structures.html#missing-values), which uses the `labelled` package. + +```{r} +negative_to_na <- function(x){ + na_range(x) <- c(-Inf, -1) + user_na_to_na(x) +} + +df_ghq_long %>% + mutate(ghq12 = negative_to_na(ghq12)) # Replaces negative values with NA +``` + +# Coda: Defining the Sample with the Longitudinal File + +A cohort member only appears in a sweep's files if they took part in that sweep. The combined datasets created above therefore only include cohort members who took part in at least one of the sweeps used, and do not tell us *why* a cohort member has no data for a particular sweep. This is especially relevant in Next Steps because [an ethnic minority boost sample was added to the study at Sweep 4](https://cls-data.github.io/docs/next_steps-data_structures.html). Boost sample members have no data for Sweeps 1-3 because they were not yet part of the study, not because they did not respond. + +The file `safeguarded_eul/ns9_2022_longitudinal_file.dta` contains one row for every cohort member, along with the fieldwork outcome at each sweep (`W1OUTCOME`, `W2OUTCOME`, ..., `W9OUTCOME`) and a variable indicating whether the cohort member belongs to the original or boost sample (`MAINBOOST`). (Boost sample members can also be identified with the variable `W4Boost` in `wave_four_lsype_young_person_2020.dta`.) It is good practice to begin with this file and merge other data onto it with `left_join()`, so that the dataset contains all cohort members. Below, we load the file, tabulate `MAINBOOST`, and merge on the wide GHQ-12 dataset created above (latter output not shown). Note, we can use regular expressions in `col_select` (via `matches()`) to select several variables at once. + +```{r} +df_longitudinal <- read_dta("safeguarded_eul/ns9_2022_longitudinal_file.dta", + col_select = c("NSID", "MAINBOOST", matches("^W\\dOUTCOME$"))) + +df_longitudinal %>% + count(MAINBOOST) +``` + +```{r} +#| output: false +df_longitudinal %>% + left_join(df_ghq_wide, by = "NSID") +``` + +The boost sample can then be dropped with `filter(MAINBOOST == 1)` (`filter()` filters *in*) where an analysis uses data from Sweeps 1-3. diff --git a/quarto/next_steps-merging_within_sweep.qmd b/quarto/next_steps-merging_within_sweep.qmd new file mode 100644 index 0000000..6e6fcdd --- /dev/null +++ b/quarto/next_steps-merging_within_sweep.qmd @@ -0,0 +1,138 @@ +--- +layout: default +title: "Combining Data Within A Sweep" +nav_order: 5 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + +- [Download the R script for this page](../purl/next_steps-merging_within_sweep.R) +- [Download the equivalent Stata script for this page](../do_files/next_steps-merging_within_sweep.do) + +# Introduction + +In this section, we show how to merge, collapse and reshape the various data structures within a given sweep of Next Steps to create a dataset at the cohort member-level (i.e., one row per cohort member). This is likely to be the most useful data structure for most analyses. + +[Most Next Steps files already have one row per cohort member](https://cls-data.github.io/docs/next_steps-data_structures.html) and all files are linked with a single identifier, `NSID`, so combining data within a sweep is more straightforward than in, e.g., the [MCS](https://cls-data.github.io/docs/mcs-merging_within_sweep.html). There are two complications. First, information about cohort members' parents is stored in separate variables for the "main parent" and "second parent", so some work is required to create variables that summarise both parents or that relate to a particular parent (such as the mother). Second, a small number of files - notably the household grid - have more than one row per cohort member and need to be collapsed before they are merged with other data. + +We use the following packages: + +```{r} +#| warning: false +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +``` + +```{r} +#| include: false +# setwd(Sys.getenv("next_steps_fld")) +``` + +# Data Cleaning + +We create a small dataset that contains information from Sweep 1 on: the cohort member's sex and attitude to school, housing tenure, family social class (National Statistics Socio-economic Classification; NS-SEC), mother's social class, and the number of siblings living with the cohort member. Constructing and combining these variables involves restructuring the data in various ways, and spans the most common data engineering tasks involved in bringing together information from a single sweep. + +The datasets we use in this tutorial are below. Note, the household grid is stored in a different subfolder to the young person and family background files. + +```{r} +yp <- read_dta("safeguarded_eul/wave_one_lsype_young_person_2020.dta") # One row per cohort member +family <- read_dta("safeguarded_eul/wave_one_lsype_family_background_2020.dta") # One row per cohort member +hhgrid <- read_dta("household_grids/wave_one_lsype_household_grid_file_2020.dta") # One row per household member +``` + +We begin with the simplest variables: the cohort member's sex and their attitude to school. These are stored in a cohort-member level dataset already (`wave_one_lsype_young_person_2020`), so they do not need further processing. Below we rename the relevant variables and select them along with the cohort member identifier, `NSID`. + +```{r} +df_yp <- yp %>% + select(NSID, sex = W1sexYP, school_attitude = W1yschat1) # Retains the listed variables, renaming W1sexYP as sex and W1yschat1 as school_attitude + +df_yp +``` + +Housing tenure is a characteristic of the household and is stored in the family background file (`wave_one_lsype_family_background_2020`). As there is one cohort member per family in Next Steps, this file also has one row per cohort member, and the variable does not need any further processing at this stage. + +```{r} +df_tenure <- family %>% + select(NSID, tenure = W1hous12HH) +``` + +Next, we create a variable for family social class using data on both parents. The family background file contains the NS-SEC of the main parent (`W1nssecMP`) and the second parent (`W1nssecSP`). As these are stored in separate *columns* (rather than separate rows), we can create a summary variable by operating across the columns. We first replace values outside the range 1-8 with `NA` (negative values denote various forms of missingness - for instance, `-98` indicates there is no second parent in the household). We then take the minimum of the two variables using `pmin()` (lower values of NS-SEC indicate higher social class). `pmin()` returns the minimum for each row; the argument `na.rm = TRUE` means that where NS-SEC is only available for one parent, that parent's value is used.[^1] + +[^1]: `wave_one_lsype_family_background_2020` also contains a derived variable for family NS-SEC, `W1nssecfam`, which is instead based on the occupation of the household reference person. We create our own variable here to demonstrate the principle, which can be applied to any pair of `MP` and `SP` variables. + +```{r} +df_nssec <- family %>% + select(NSID, W1nssecMP, W1nssecSP) %>% + mutate(across(c(W1nssecMP, W1nssecSP), + ~ if_else(between(.x, 1, 8), as.numeric(.x), NA))) %>% # Values outside 1-8 denote various forms of missingness + mutate(family_nssec = pmin(W1nssecMP, W1nssecSP, na.rm = TRUE)) %>% # Takes the lowest value of the two variables in each row + select(NSID, family_nssec) + +df_nssec +``` + +We next show a different way of using the main and second parent variables: reshaping the data from wide to long so that we have one row per *parent*. This is useful where we want to create a variable for a particular parent - in this case, the cohort member's mother. [The main and second parent are roles in the interview](https://cls-data.github.io/docs/next_steps-data_structures.html), and either could be the cohort member's mother, so we need to bring in information from the household grid to find out who each parent is. + +The family background file contains the variables `W1mainres` and `W1secores`, which record the person number of the main and second parent in the household grid. Below, we first rename these variables so that they follow the same convention as the NS-SEC variables (a common stem, followed by `MP` or `SP`). We then reshape the data from [wide to long using `pivot_longer()`](https://r4ds.hadley.nz/data-tidy.html#sec-pivoting). The `names_pattern` argument uses a regular expression to split the variable names into two pieces: the stem (`"(.*)"`) and the suffix (`"(MP|SP)"`). The stem is used to name the new columns (`.value`) and the suffix is stored in a new variable, `parent`. The result is a dataset with two rows per cohort member, one for each parent.[^2] + +[^2]: We use `zap_labels()` to remove value labels from the variables prior to reshaping. `pivot_longer()` stacks the main and second parent variables on top of each other, and will print a warning where their value labels are not identical. For more on reshaping data, see [*Reshaping Data from Long to Wide (or Wide to Long)*](https://cls-data.github.io/docs/next_steps-reshape_long_wide.html). + +```{r} +df_parent <- family %>% + select(NSID, W1HhIDMP = W1mainres, W1HhIDSP = W1secores, W1nssecMP, W1nssecSP) %>% + zap_labels() %>% # Removes value labels + pivot_longer(cols = -NSID, # Reshape all columns except NSID + names_to = c(".value", "parent"), + names_pattern = "^(.*)(MP|SP)$") + +df_parent +``` + +`df_parent` now contains the person number of each parent (`W1HhID`). We can use this to merge in each parent's sex (`W1Sex`) and relationship to the cohort member (`W1R_1`) from the household grid (see [*Working with the Household Grid*](https://cls-data.github.io/docs/next_steps-household_grid.html)). We use `inner_join()` so that we only keep rows where the parent is found in the household grid (this drops, for instance, rows for second parents in families where there is no second parent). We then keep the rows for natural mothers (`W1R_1 == 8` \[Natural parent\] and `W1Sex == 2` \[Female\]). The result is a dataset with one row per cohort member whose natural mother was the main or second parent, containing the mother's NS-SEC.[^3] + +[^3]: More detail on merging with `inner_join()` (and other `*_join()` variants) is provided in [*Combining Data Across Sweeps*](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html), as well as [Chapter 19 of the R for Data Science textbook](https://r4ds.hadley.nz/joins.html#sec-mutating-joins). Note, for many characteristics, the family background file already contains derived variables for mothers and fathers - in this case, `W1nssecmum` and `W1nssecdad`. The approach here is needed for `MP` and `SP` variables that do not have such an equivalent. + +```{r} +df_mother_nssec <- hhgrid %>% + select(NSID, W1HhID, W1Sex, W1R_1) %>% + inner_join(df_parent, by = c("NSID", "W1HhID")) %>% + filter(W1R_1 == 8, # Keep natural parents... + W1Sex == 2) %>% # ...who are female + add_count(NSID) %>% # Creates new variable (n) containing # of records with given NSID + filter(n == 1) %>% # Keep where only one natural mother identified per cohort member + mutate(mother_nssec = if_else(between(W1nssec, 1, 8), W1nssec, NA)) %>% + select(NSID, mother_nssec) +``` + +Finally, we create a variable for the number of siblings living with the cohort member. This involves collapsing the household grid, which has one row per household member, so that it has one row per cohort member. `W1R_1` records each household member's relationship to the cohort member, with values between 13 and 17 indicating different types of sibling (natural, half-, step-, adopted and foster siblings). We count the number of rows that meet this condition using `summarise()` on a [grouped data frame](https://r4ds.hadley.nz/data-transform.html#groups) (`group_by(NSID)`) to ensure this is calculated per cohort member. + +```{r} +df_siblings <- hhgrid %>% + select(NSID, W1HhID, W1R_1) %>% + group_by(NSID) %>% # Groups the data so summarise() is performed per cohort member + summarise(n_siblings = sum(W1R_1 %in% 13:17), # Counts the number of rows where W1R_1 is between 13 and 17 + .groups = "drop") # Removes the grouping from the resulting dataframe + +df_siblings +``` + +The same principles apply to the "hierarchical" files from Sweeps 8 and 9 - for instance, `ns8_2015_children.dta`, which has one row for each of the cohort member's children. Note, though, that cohort members only appear in these files if they have at least one record (e.g., at least one child), so some care is needed when merging the collapsed data with other files: cohort members who do not appear in the file should typically be assigned a count of zero, rather than `NA`. + +# Merging the Datasets + +Now we have cleaned each variable, we can merge them together. The cleaned datasets are all at the cohort member level. We begin with `df_yp` as this has all the cohort members participating at Sweep 1 in it. We then use `left_join()` to merge in other data so original rows are kept (and no more are added). As `NSID` uniquely identifies cohort members, we use `left_join(..., by = "NSID")` in each case. + +```{r} +df_yp %>% + left_join(df_tenure, by = "NSID") %>% + left_join(df_nssec, by = "NSID") %>% + left_join(df_mother_nssec, by = "NSID") %>% + left_join(df_siblings, by = "NSID") +``` + +As noted in [*Combining Data Across Sweeps*](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html), `left_join()` will not throw an error if a cohort member appears more than once in one of the datasets - it will simply add rows. If you want `R` to enforce that each row is matched to at most one row in the other dataset, you can add the argument `relationship = "one-to-one"` to the `*_join()` function call. + +# Footnotes diff --git a/quarto/next_steps-reshape_long_wide.qmd b/quarto/next_steps-reshape_long_wide.qmd new file mode 100644 index 0000000..b5c9a5c --- /dev/null +++ b/quarto/next_steps-reshape_long_wide.qmd @@ -0,0 +1,120 @@ +--- +layout: default +title: "Reshaping Data from Long to Wide (or Wide to Long)" +nav_order: 6 +parent: Next Steps +format: + gfm: + variant: +yaml_metadata_block +--- + +- [Download the R script for this page](../purl/next_steps-reshape_long_wide.R) +- [Download the equivalent Stata script for this page](../do_files/next_steps-reshape_long_wide.do) + +# Introduction + +In this section, we show how to reshape data from long to wide (and vice versa). We do this for both raw and cleaned data. To demonstrate, we use data on cohort members' height and weight collected in Sweeps 8 and 9 (ages 25 and 32). + +The packages we use are: + +```{r} +#| warning: false +# Load Packages +library(tidyverse) # For data manipulation +library(haven) # For importing .dta files +``` + +```{r} +#| include: false +# setwd(Sys.getenv("next_steps_fld")) +``` + +# Reshaping Raw Data from Wide to Long + +We begin by loading the data from each sweep and merging these together into a single wide format data frame; see [Combining Data Across Sweeps](https://cls-data.github.io/docs/next_steps-merging_across_sweeps.html) for further explanation on how this is achieved. Height and weight are stored in the main interview files for Sweeps 8 and 9 (`ns8_2015_main_interview.dta` and `ns9_2022_main_interview.dta`, both in the `safeguarded_eul` subfolder). The names of the height and weight variables follow the same convention in the two sweeps, differing only in the prefix that denotes the sweep (`W8HEIGHT` and `W9HEIGHT`; `W8WEIGHT` and `W9WEIGHT`). This is typical for variables collected in Sweeps 8 and 9, but [not for variables collected in both earlier and later sweeps](https://cls-data.github.io/docs/next_steps-data_structures.html), which usually need to be renamed before they can be reshaped. + +```{r} +df_w8 <- read_dta("safeguarded_eul/ns8_2015_main_interview.dta", + col_select = c("NSID", "W8HEIGHT", "W8WEIGHT")) + +df_w9 <- read_dta("safeguarded_eul/ns9_2022_main_interview.dta", + col_select = c("NSID", "W9HEIGHT", "W9WEIGHT")) + +df_wide <- df_w8 %>% + full_join(df_w9, by = "NSID") + +df_wide +``` + +`df_wide` has 5 columns. Besides the identifier, `NSID`, there are 4 columns for height and weight measurements at each sweep. Each of these 4 columns is prefixed by the letter `W` and a single digit indicating the sweep. We can reshape the dataset into long format (one row per person x sweep combination) using the `pivot_longer()` function so that the resulting data frame has four columns: one person identifier, a variable for sweep, and variables for height and weight. We specify the columns to be reshaped using the `cols` argument, provide the new variable names in the `names_to` argument, and the pattern the existing column names take using the `names_pattern` argument. For `names_pattern` we specify `"^W(\\d)(.*)$"`, which breaks the column name into two pieces: the digit following the initial `W` (`"(\\d)"`) and the rest of the name (`"(.*)"`). `names_pattern` uses regular expressions.[^1] `\\d` is a special character denoting a digit, `.` matches single characters, and `.*` modifies this to match zero or more characters. As noted, the digit holds information on sweep; in the reshaped data frame the digit is stored as a value in a new column `sweep`. `.value` is a placeholder for the new columns in the reshaped data frame that store the values from the columns selected by `cols`; these new columns are named using the second piece from `names_pattern` - in this case `HEIGHT` and `WEIGHT`. Finally, we use the `names_transform` argument to convert `sweep` to an integer. As the values of `sweep` are taken from the column names, they would otherwise be stored as text (`"8"` and `"9"`), which is harder to work with: text cannot be used in calculations, is sorted alphabetically rather than numerically, and cannot be matched to a numeric sweep variable when merging with other datasets. + +[^1]: Regular expressions are extremely useful and compact ways of working with text. See [Chapter 15 in the R for Data Science textbook](https://r4ds.hadley.nz/regexps.html) for more information. ChatGPT and similar services are very useful for writing and interpreting regular expressions. + +```{r} +#| warning: false +df_long <- df_wide %>% + pivot_longer(cols = matches("^W\\d(HEIGHT|WEIGHT)$"), + names_to = c("sweep", ".value"), + names_pattern = "^W(\\d)(.*)$", + names_transform = list(sweep = as.integer)) + +df_long +``` + +Note, in the original `df_wide` tibble, the height and weight variables were labelled numeric vectors - this class allows users to add metadata to variables (value labels, etc.). When reshaping to long format, multiple variables are effectively appended together, so the final reshaped variables can only have one set of properties. `pivot_longer()` tries to preserve variable attributes, but in some cases will throw an error (where variables are of inconsistent types) or print a warning (where value labels are inconsistent). This is the case here: the value labels attached to the Sweep 8 and Sweep 9 variables are not identical, so running the `pivot_longer()` code above produces a warning that the variables have conflicting value labels, and the labels from the Sweep 8 variables are used. Where this is a concern, value labels can be removed prior to reshaping with `zap_labels()` (from `haven`). + +# Reshaping Raw Data from Long to Wide + +We can also reshape the data from long to wide format using the `pivot_wider()` function. In this case, we want to create two new columns for each sweep: one for height and one for weight. We specify the columns to be reshaped using the `values_from` argument, provide the old column names in the `names_from` argument, and use the `names_glue` argument to specify the convention to follow for the new column names. The `names_glue` argument uses curly braces (`{}`) to reference the values from the `names_from` and `.value` arguments. As we are specifying multiple columns in `values_from`, `.value` is a placeholder for the names of the variables selected in `values_from`. + +```{r} +df_long %>% + pivot_wider(names_from = sweep, + values_from = c(HEIGHT, WEIGHT), + names_glue = "W{sweep}{.value}") +``` + +# Reshaping Cleaned Data from Long to Wide + +It is likely that you will not just need to reshape raw data, but cleaned data too. In the next two sections we offer advice on naming variables so that they are easy to select and reshape in long or wide formats. First, we clean the long dataset by creating a new column for the cohort member's age at each sweep, and creating new `height` and `weight` variables that replace negative values in the raw height and weight data with `NA` (as well as giving these variables more easy-to-understand names). To create the age variable, we create a vector, `ages`, which contains the (approximate) age of cohort members at each of the nine sweeps, and subset it using the sweep number (i.e., `ages[8]` returns `25`). + +```{r} +ages <- c(14, 15, 16, 17, 18, 19, 20, 25, 32) + +df_long_clean <- df_long %>% + mutate(age = ages[sweep], + height = ifelse(HEIGHT > 0, HEIGHT, NA), + weight = ifelse(WEIGHT > 0, WEIGHT, NA)) %>% + select(NSID, age, height, weight) + +df_long_clean +``` + +To reshape the clean data from long to wide format, we can use the `pivot_wider()` function as before. This time, we specify the column containing the cohort member's age in the `names_from` argument, the columns to be reshaped in the `values_from` argument, and use the `names_glue` argument to specify the new column names. The `names_glue` argument uses curly braces (`{}`) to reference the values from the `names_from` and `.value` arguments. As we are specifying multiple columns in `values_from`, `.value` is a placeholder for the variable name. + +```{r} +df_wide_clean <- df_long_clean %>% + pivot_wider(names_from = age, + values_from = c(height, weight), + names_glue = "{.value}_{age}") + +df_wide_clean +``` + +Notice that the new variable names consist of a descriptive stem, an underscore, and the age at measurement. A consistent convention such as this makes it simple to subset variables either by name (e.g., `select(matches("^height_\\d\\d$"))`) or by numerical range (e.g., `select(matches("^(h|w)eight_2[0-9]$"))`).[^2] As cohort members were aged between 14 and 32 in Sweeps 1-9, the age is always two characters long. In studies that include measurements from earlier in life, it is worth padding ages with a leading zero (e.g., `height_05`) so that the names of similar variables are the same length. + +[^2]: In regular expressions, `^` and `$` are special characters that match the beginning and end of a string, respectively. `"^height_\\d\\d$"` matches any string that begins "height\_", immediately followed by two digits (0, 1, ..., 9) that end the string. `"^(h|w)eight_2[0-9]$"` matches any string that begins height or weight, immediately followed by a number between 20 and 29 (`[0-9]` is a compact way of matching the integer range 0, 1, ..., 9). + +# Reshaping Cleaned Data from Wide to Long + +Finally, we can reshape the clean wide dataset back to long format using the `pivot_longer()` function. We specify the columns to be reshaped using the `cols` argument, provide the new variable names in the `names_to` argument, and the pattern the existing column names take using the `names_pattern` argument. For `names_pattern` we specify `"(.*)_(\\d\\d)$"`, which breaks the column name into two pieces: the variable name (`"(.*)"`), and the age (`"(\\d\\d)"`). As before, we use the `names_transform` argument to convert the age to an integer. Note how easy it is to identify the variables we want to reshape in `cols`: because we used a consistent naming structure for the cleaned variables, a short regular expression (`"_\\d\\d$"`) selects all of them. + +```{r} +df_wide_clean %>% + pivot_longer(cols = matches("_\\d\\d$"), + names_to = c(".value", "age"), + names_pattern = "(.*)_(\\d\\d)$", + names_transform = list(age = as.integer)) +``` + +# Footnotes