Describing a Dataset
An increase in the average depression score between visits may reflect a change in who was observed as well as a change in individual scores. To interpret it, we need to know whether the two means describe the same people. Percentages pose a related problem: including unanswered forms in the denominator changes what a reported share describes. This chapter develops descriptive summaries around the question of which observations contribute. We define the units being counted, describe numerical distributions by their center and spread, and calculate proportions with explicit denominators. We then compare groups and the same people over time, examining how inclusion and weighting affect the interpretation.
17.1 Defining the observations being described
The survey file contains 503 forms from 500 people because three people submitted twice. For a description of participation, we count each person once. If we ask what percentage of forms contain a rating for the first life-satisfaction question, SAT_1, each of the 503 forms instead counts once. Someone who submitted twice could give a rating on one form and skip the question on the other.
For test performance, even a count of trial rows is too broad. Participants press keys during practice as well as during the test, and the file for completed runs includes a questionnaire from each run. We therefore select keyboard trials in blocks 1 through 4 before describing test performance.
Counting submissions can also overstate how often a scheduled prompt was answered. In the app study, someone can answer the same prompt twice, giving two replies but only one answered prompt. We need to match replies to prompts before counting how many scheduled prompts received an answer.
ResponseId identifies a submitted form, and ID identifies the person who sent it. Reading 0091 as a number would drop its leading zeros. In R, n_distinct() counts forms or people according to which identifier it receives. For SAT_1, %in% agreement_levels tests whether a form contains one of the five ratings. The trial count combines trial_type == "keyboard" with membership in blocks 1 through 4. tribble() lists each count beside its unit and definition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
library(tidyverse)
survey <- read_csv(
"data/practice/survey.csv",
col_types = cols(`Duration (in seconds)` = col_double(), .default = col_character()),
na = "",
trim_ws = FALSE,
locale = locale(encoding = "UTF-8")
)
trials <- read_csv(
"data/practice/trials.csv",
col_types = cols_only(
participant = col_character(),
trial_type = col_character(),
block = col_integer()
),
na = "",
trim_ws = FALSE
)
schedule <- read_csv(
"data/practice/ema_schedule.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
responses <- read_csv(
"data/practice/ema_responses.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
agreement_levels <- c(
"Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"
)
survey |>
filter(ResponseId == "R_87D3ao1njf1u") |>
select(ResponseId, ID, SAT_1, SAT_2)
accounting <- tribble(
~source, ~unit, ~definition, ~n,
"survey", "response", "distinct ResponseId", n_distinct(survey$ResponseId),
"survey", "participant", "distinct ID", n_distinct(survey$ID),
"survey", "observed SAT_1", "agreement label",
sum(survey$SAT_1 %in% agreement_levels),
"trials", "record", "row", nrow(trials),
"trials", "test trial", "keyboard, blocks 1 to 4",
sum(trials$trial_type == "keyboard" & trials$block %in% 1:4),
"ema", "opportunity", "schedule row", nrow(schedule),
"ema", "submitted event", "response row", nrow(responses)
)
accounting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# A tibble: 1 × 4
ResponseId ID SAT_1 SAT_2
<chr> <chr> <chr> <chr>
1 R_87D3ao1njf1u 0091 <NA> Neutral
# A tibble: 7 × 4
source unit definition n
<chr> <chr> <chr> <int>
1 survey response distinct ResponseId 503
2 survey participant distinct ID 500
3 survey observed SAT_1 agreement label 492
4 trials record row 8040
5 trials test trial keyboard, blocks 1 to 4 7680
6 ema opportunity schedule row 4200
7 ema submitted event response row 3323
In Polars, n_unique() counts forms when applied to ResponseId and people when applied to ID. Both identifiers are read as strings, so 0091 includes its leading zeros. For SAT_1, is_in(agreement_levels).sum() counts forms with one of the five agreement labels. The trial table’s height counts every record, while filter(is_test).height counts only keyboard trials in blocks 1 through 4. The schedule and submission totals each have their own row in accounting.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import polars as pl
survey = pl.read_csv(
"data/practice/survey.csv",
infer_schema=False,
schema_overrides={"Duration (in seconds)": pl.Int64},
empty_string_is_null=True,
encoding="utf8",
)
trials = pl.read_csv(
"data/practice/trials.csv",
columns=["participant", "trial_type", "block"],
infer_schema=False,
schema_overrides={"block": pl.Int64},
)
schedule = pl.read_csv("data/practice/ema_schedule.csv", infer_schema=False)
responses = pl.read_csv("data/practice/ema_responses.csv", infer_schema=False)
agreement_levels = [
"Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"
]
survey.filter(pl.col("ResponseId") == "R_87D3ao1njf1u").select(
"ResponseId", "ID", "SAT_1", "SAT_2"
)
is_test = (pl.col("trial_type") == "keyboard") & pl.col("block").is_in([1, 2, 3, 4])
accounting = pl.DataFrame(
{
"source": ["survey", "survey", "survey", "trials", "trials", "ema", "ema"],
"unit": [
"response",
"participant",
"observed SAT_1",
"record",
"test trial",
"opportunity",
"submitted event",
],
"definition": [
"distinct ResponseId",
"distinct ID",
"agreement label",
"row",
"keyboard, blocks 1 to 4",
"schedule row",
"response row",
],
"n": [
survey["ResponseId"].n_unique(),
survey["ID"].n_unique(),
survey["SAT_1"].is_in(agreement_levels).sum(),
trials.height,
trials.filter(is_test).height,
schedule.height,
responses.height,
],
}
)
accounting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
shape: (1, 4)
┌────────────────┬──────┬───────┬─────────┐
│ ResponseId ┆ ID ┆ SAT_1 ┆ SAT_2 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞════════════════╪══════╪═══════╪═════════╡
│ R_87D3ao1njf1u ┆ 0091 ┆ null ┆ Neutral │
└────────────────┴──────┴───────┴─────────┘
shape: (7, 4)
┌────────┬─────────────────┬─────────────────────────┬──────┐
│ source ┆ unit ┆ definition ┆ n │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 │
╞════════╪═════════════════╪═════════════════════════╪══════╡
│ survey ┆ response ┆ distinct ResponseId ┆ 503 │
│ survey ┆ participant ┆ distinct ID ┆ 500 │
│ survey ┆ observed SAT_1 ┆ agreement label ┆ 492 │
│ trials ┆ record ┆ row ┆ 8040 │
│ trials ┆ test trial ┆ keyboard, blocks 1 to 4 ┆ 7680 │
│ ema ┆ opportunity ┆ schedule row ┆ 4200 │
│ ema ┆ submitted event ┆ response row ┆ 3323 │
└────────┴─────────────────┴─────────────────────────┴──────┘
On the form shown for participant 0091, Neutral answers the second question. The first is blank, so this form counts toward the 503 submissions and contributes no rating for SAT_1.
Of the 503 forms, 492 contain a rating for SAT_1, or 97.8 percent. The item is blank on ten forms, and one form records a refusal. Thus the number of submitted forms and the number of observed ratings answer different questions.
In the trial file, 7,680 of 8,040 records are keyboard test trials. The other records are 320 practice trials and 40 questionnaires, which do not belong in a count of test responses.
The app scheduled 4,200 prompts and received 3,323 submissions. Those totals alone cannot determine the number of unanswered prompts: subtracting them would assume that every submission answered a different scheduled prompt. That count requires replies to be linked to the schedule, with each prompt counted once according to whether it received a match.
17.2 Describing a numerical distribution
Once we have defined the observations, a numerical distribution describes which values occur and how often. Consider five scores: 2, 3, 4, 5, and 20. Their mean is the sum divided by the count, 34/5 = 6.8, while their median is the middle score in order, 4. The largest score affects these measures differently: replacing 20 with 200 would raise the mean to 42.8 while the median would still be 4.
Quartiles describe the spread around the center. The first and third quartiles mark the 25th and 75th percentile positions among the ordered scores. For these five scores, they are 3 and 5. Their difference, the interquartile range, is 2. It measures the width of the middle half of the distribution. Replacing 20 with 200 would leave both quartiles unchanged.
To calculate quartiles consistently, we need a rule for positions between scores. A quantile marks a relative position among the ordered values, with the proportion p running from 0 at the lowest rank to 1 at the highest. Under the linear rule used here, its position among n scores is 1 + (n - 1)p, counting from 1. With our five scores, p values of 0.25, 0.5, and 0.75 give positions 2, 3, and 4. With four scores, however, the first quartile falls at position 1.75. Its value is three quarters of the way from the first score to the second. This calculation is linear interpolation.
A second measure of spread describes distances from the mean. Subtracting 6.8 from each score gives deviations of -4.8, -3.8, -2.8, -1.8, and 13.2. Their squares are 23.04, 14.44, 7.84, 3.24, and 174.24. The largest score alone contributes 174.24 to their sum of 222.8. For the sample variance, we divide that sum by n - 1, here 4, giving 55.7.
Variance is expressed in squared units: for scores measured in points, it is measured in squared points. Taking the square root gives the standard deviation, about 7.46 points, in the original unit. Unlike the interquartile range, this measure incorporates the distance of every score from the mean.
Before applying these calculations to the panel data, we also need to establish what they return when few scores are available. An empty input has no entries to count as observed or missing, and no mean, median, or quartiles. With one value, the mean, median, and quartiles equal it and the interquartile range is zero. Sample variance cannot be computed because its denominator n - 1 is zero.
In R, describe_values() returns counts and summaries in one row. quantile(type = 7) implements the chosen linear convention, while names = FALSE removes its percentile label, such as 25%. A tibble evaluates columns in order, allowing iqr to use q1 and q3. var() and sd() use the sample denominator. bind_rows() stacks the five-value, empty, and single-value calls. Named arguments and .id label their inputs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
describe_values <- function(x) {
tibble(
n_observed = sum(!is.na(x)),
n_unavailable = sum(is.na(x)),
mean = mean(x, na.rm = TRUE),
median = median(x, na.rm = TRUE),
q1 = quantile(x, 0.25, type = 7, na.rm = TRUE, names = FALSE),
q3 = quantile(x, 0.75, type = 7, na.rm = TRUE, names = FALSE),
iqr = q3 - q1,
variance = var(x, na.rm = TRUE)
)
}
values <- c(2, 3, 4, 5, 20)
values
(values - mean(values))^2
sum((values - mean(values))^2) / (length(values) - 1)
sd(values)
bind_rows(
five = describe_values(values),
none = describe_values(numeric(0)),
one = describe_values(5),
.id = "input"
)
1
2
3
4
5
6
7
8
9
10
[1] 2 3 4 5 20
[1] 23.04 14.44 7.84 3.24 174.24
[1] 55.7
[1] 7.463243
# A tibble: 3 × 9
input n_observed n_unavailable mean median q1 q3 iqr variance
<chr> <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 five 5 0 6.8 4 3 5 2 55.7
2 none 0 0 NaN NA NA NA NA NA
3 one 1 0 5 5 5 5 0 NA
The five row gives a mean of 6.8 and a median of 4. For the empty vector, the mean is NaN and the other measures are NA. With one score, the interquartile range is zero and the variance is unavailable.
We can now apply the same summaries to data/practice/panel_wide.csv, where each row represents one person. The column dep_w1 contains the depression total at wave 1, on a scale from 0 to 18 points. read_csv() reads these totals as integers and treats blank fields as missing.
The count of missing totals needs interpretation as well. Participants with IDs from 0301 to 0315 joined at wave 2, so they had no wave-1 visit. Counting missing totals by entry wave distinguishes them from people who attended wave 1 but have no recorded score.
1
2
3
4
5
6
7
8
9
10
11
12
13
panel <- read_csv(
"data/practice/panel_wide.csv",
col_types = cols(dep_w1 = col_integer(), .default = col_character()),
na = "",
trim_ws = FALSE
)
nrow(panel)
baseline_summary <- describe_values(panel$dep_w1)
baseline_summary
sd(panel$dep_w1, na.rm = TRUE)
panel |>
filter(is.na(dep_w1)) |>
count(entry_wave = if_else(id >= "0301", 2L, 1L))
1
2
3
4
5
6
7
8
9
10
11
[1] 315
# A tibble: 1 × 8
n_observed n_unavailable mean median q1 q3 iqr variance
<int> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 276 39 6.64 6 2 10 8 25.9
[1] 5.092415
# A tibble: 2 × 2
entry_wave n
<int> <int>
1 1 24
2 2 15
The describe() function below builds a list of Polars expressions for a named numeric column. count() counts observed values and null_count() counts missing ones. The default for quantile() in Polars is interpolation="nearest"; specifying interpolation="linear" applies the rule derived above. The difference q3 - q1 gives the interquartile range. In var() and std(), ddof=1 gives the sample denominator.
The three calls check which summaries are defined for five values, no values, and one value. They also show how unavailable results appear in the output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def describe(column):
value = pl.col(column)
q1 = value.quantile(0.25, interpolation="linear")
q3 = value.quantile(0.75, interpolation="linear")
return [
value.count().alias("n_observed"),
value.null_count().alias("n_unavailable"),
value.mean().alias("mean"),
value.median().alias("median"),
q1.alias("q1"),
q3.alias("q3"),
(q3 - q1).alias("iqr"),
value.var(ddof=1).alias("variance"),
]
values = pl.DataFrame({"value": [2.0, 3.0, 4.0, 5.0, 20.0]})
values["value"].to_list()
values["value"].std(ddof=1)
empty = pl.DataFrame({"value": []}, schema={"value": pl.Float64})
single = pl.DataFrame({"value": [5.0]})
pl.concat([frame.select(describe("value")) for frame in (values, empty, single)])
1
2
3
4
5
6
7
8
9
10
11
12
[2.0, 3.0, 4.0, 5.0, 20.0]
7.463243262818116
shape: (3, 8)
┌────────────┬───────────────┬──────┬────────┬──────┬──────┬──────┬──────────┐
│ n_observed ┆ n_unavailable ┆ mean ┆ median ┆ q1 ┆ q3 ┆ iqr ┆ variance │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪═══════════════╪══════╪════════╪══════╪══════╪══════╪══════════╡
│ 5 ┆ 0 ┆ 6.8 ┆ 4.0 ┆ 3.0 ┆ 5.0 ┆ 2.0 ┆ 55.7 │
│ 0 ┆ 0 ┆ null ┆ null ┆ null ┆ null ┆ null ┆ null │
│ 1 ┆ 0 ┆ 5.0 ┆ 5.0 ┆ 5.0 ┆ 5.0 ┆ 0.0 ┆ null │
└────────────┴───────────────┴──────┴────────┴──────┴──────┴──────┴──────────┘
In the five-score row, the mean is 6.8, the median is 4, and the variance is 55.7. The empty input has no scores to average, so its mean and other measures are null. In the row with one score, both quartiles equal 5 and the interquartile range is zero, while the sample variance is null.
We can now apply the same summaries to data/practice/panel_wide.csv, where each row represents one person. The column dep_w1 is the wave-1 depression total on a scale from 0 to 18 points. After it is read as pl.Int64, select(describe("dep_w1")) summarizes the observed totals and counts the nulls.
The count of missing totals needs interpretation as well. Participants with IDs from 0301 to 0315 joined at wave 2. Counting nulls by entry wave separates these later entrants from people with a blank total at their first visit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
panel = pl.read_csv(
"data/practice/panel_wide.csv",
infer_schema=False,
schema_overrides={"dep_w1": pl.Int64},
)
panel.height
baseline_summary = panel.select(describe("dep_w1"))
baseline_summary
panel["dep_w1"].std(ddof=1)
(
panel.filter(pl.col("dep_w1").is_null())
.group_by(entry_wave=pl.when(pl.col("id") >= "0301").then(2).otherwise(1))
.agg(n=pl.len())
.sort("entry_wave")
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
315
shape: (1, 8)
┌────────────┬───────────────┬──────────┬────────┬─────┬──────┬─────┬───────────┐
│ n_observed ┆ n_unavailable ┆ mean ┆ median ┆ q1 ┆ q3 ┆ iqr ┆ variance │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪═══════════════╪══════════╪════════╪═════╪══════╪═════╪═══════════╡
│ 276 ┆ 39 ┆ 6.641304 ┆ 6.0 ┆ 2.0 ┆ 10.0 ┆ 8.0 ┆ 25.932688 │
└────────────┴───────────────┴──────────┴────────┴─────┴──────┴─────┴───────────┘
5.092414726535495
shape: (2, 2)
┌────────────┬─────┐
│ entry_wave ┆ n │
│ --- ┆ --- │
│ i32 ┆ u32 │
╞════════════╪═════╡
│ 1 ┆ 24 │
│ 2 ┆ 15 │
└────────────┴─────┘
The panel has wave-1 totals for 276 of the 315 people. Of the 39 without a score, 15 joined at wave 2 and had no first-wave visit. The other 24 attended wave 1 but have a blank total. The summary therefore describes the 276 people with recorded totals.
Among those totals, the mean is about 6.64 points and the median is 6. The quartiles of 2 and 10 give an interquartile range of 8 points. The standard deviation is about 5.09 points and the variance is about 25.93 squared points. These summaries use dep_w1 as supplied, without recomputing the totals from individual items.
17.3 Frequencies, proportions, and cross-classifications
The numerical summaries used the people with observed scores. For a categorical variable, we must likewise decide whether the denominator includes observations with no recorded answer. What proportion of the forms in Table 17.1 report Female: two out of all five forms, or two out of the four that give a gender?
Table 17.1. Gender and region on five constructed survey forms.
| Response | Gender | Region |
|---|---|---|
| r1 | Female | Seoul |
| r2 | Female | Busan |
| r3 | Male | Seoul |
| r4 | Male | Seoul |
| r5 | missing | Busan |
Two of the five forms report Female. That count is the category’s frequency. Its proportion among all forms is 2/5, or 40 percent. Among forms with a recorded gender, the same two make up 2/4, or 50 percent.
We can also ask how gender and region occur together. A two-way table, or cross-classification, counts observations for each combination of two variables. Here the rows are gender categories and the columns are regions. A percentage within a row and a percentage within a column answer different questions.
Only r1 reports both Female and Seoul. Of the two forms marked Female, one reports Seoul, so the row percentage is 50 percent. Of the three Seoul forms, one reports Female, so the column percentage is about 33.3 percent. Missing gender has its own row.
A zero count also needs its denominator. Neither Busan form reports Male, so the Male percentage among Busan forms is zero. Jeju is a possible region, but none of the five forms reports it. With a column total of zero, its column percentages are undefined.
Before counting categories in the survey file, we must reconcile labels that represent the same category, such as F and Female. After spaces are trimmed and labels lowercased, recode_values() maps f/female to Female, m/male to Male, and other to Other. Blanks remain missing.
For each category in count(), of_responses gives the percentage of all forms and of_observed the percentage of forms with recorded gender. The missing category has only the first percentage, because it is excluded from the second denominator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
gender_dictionary <- tibble(
working = c("f", "female", "m", "male", "other"),
category = c("Female", "Female", "Male", "Male", "Other")
)
genders <- survey |>
select(ResponseId, Gender, Region) |>
mutate(
gender = recode_values(
str_to_lower(str_trim(Gender)),
from = gender_dictionary$working,
to = gender_dictionary$category
)
)
gender_counts <- count(genders, gender) |>
mutate(
of_responses = 100 * n / sum(n),
of_observed = if_else(is.na(gender), NA_real_, 100 * n / sum(n[!is.na(gender)]))
)
gender_counts
1
2
3
4
5
6
7
# A tibble: 4 × 4
gender n of_responses of_observed
<chr> <int> <dbl> <dbl>
1 Female 235 46.7 47
2 Male 252 50.1 50.4
3 Other 13 2.58 2.6
4 <NA> 3 0.596 NA
Of the 503 forms, 235 report Female, or 46.7 percent. Three forms have no recorded gender. Among the 500 forms that give a gender, the same 235 make up 47 percent.
The margins of a two-way table are its row and column totals. In add_margins(), .by = gender groups the counts for sum(n) by gender to give row totals; grouping by region gives column totals. Each percentage uses its corresponding total only when that total is positive.
The table must also represent combinations with no forms. For the five-form example, complete() includes all three listed regions, even Jeju. For the survey, it pairs every observed gender category with every observed region, including missing categories. Combinations with no forms receive a count of zero.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
add_margins <- function(cells) {
cells |>
mutate(row_total = sum(n), .by = gender) |>
mutate(column_total = sum(n), .by = region) |>
mutate(
row_percent = if_else(row_total > 0, 100 * n / row_total, NA_real_),
column_percent = if_else(column_total > 0, 100 * n / column_total, NA_real_)
)
}
five <- tibble(
response = c("r1", "r2", "r3", "r4", "r5"),
gender = c("Female", "Female", "Male", "Male", NA),
region = c("Seoul", "Busan", "Seoul", "Seoul", "Busan")
)
five |>
count(gender, region) |>
complete(gender, region = c("Seoul", "Busan", "Jeju"), fill = list(n = 0L)) |>
add_margins()
survey_cells <- genders |>
count(gender, region = Region) |>
complete(gender, region, fill = list(n = 0L)) |>
add_margins()
c(
cells = nrow(survey_cells),
zero_cells = sum(survey_cells$n == 0),
responses = sum(survey_cells$n)
)
survey_cells |>
filter(
(gender == "Female" & region == "Seoul") |
(gender == "Other" & region == "Busan") |
(is.na(gender) & region == "Busan") |
(gender == "Female" & is.na(region))
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# A tibble: 9 × 7
gender region n row_total column_total row_percent column_percent
<chr> <chr> <int> <int> <int> <dbl> <dbl>
1 Female Busan 1 2 2 50 50
2 Female Jeju 0 2 0 0 NA
3 Female Seoul 1 2 3 50 33.3
4 Male Busan 0 2 2 0 0
5 Male Jeju 0 2 0 0 NA
6 Male Seoul 2 2 3 100 66.7
7 <NA> Busan 1 1 2 100 50
8 <NA> Jeju 0 1 0 0 NA
9 <NA> Seoul 0 1 3 0 0
cells zero_cells responses
72 29 503
# A tibble: 4 × 7
gender region n row_total column_total row_percent column_percent
<chr> <chr> <int> <int> <int> <dbl> <dbl>
1 Female Seoul 48 235 90 20.4 53.3
2 Female <NA> 4 235 4 1.70 100
3 Other Busan 0 13 27 0 0
4 <NA> Busan 1 3 27 33.3 3.70
In the five-form example, neither of the two Busan forms reports Male, so the Male share in Busan is 0 percent. Jeju has no forms at all, so its column percentages are unavailable. In the survey table, 29 of the 72 combinations have no responses. The counts across all 72 sum to 503.
Before counting categories in the survey file, we reconcile different labels for the same category. str.strip_chars(" ") removes surrounding spaces, str.to_lowercase() converts labels to lowercase, and the dictionary in replace_strict() maps both f and female to Female.
In the grouped table, n counts forms per category. Summing all four counts gives the denominator for all forms. Summing only the counts with a recorded gender gives the denominator for of_observed. That percentage is null for the missing-gender group, which is excluded from its denominator.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
gender_dictionary = {
"f": "Female",
"female": "Female",
"m": "Male",
"male": "Male",
"other": "Other",
}
genders = survey.select("ResponseId", "Gender", "Region").with_columns(
gender=pl.col("Gender")
.str.strip_chars(" ")
.str.to_lowercase()
.replace_strict(gender_dictionary, default=None)
)
observed = pl.col("gender").is_not_null()
gender_counts = (
genders.group_by("gender")
.agg(n=pl.len())
.with_columns(
of_responses=100 * pl.col("n") / pl.col("n").sum(),
of_observed=pl.when(observed).then(
100 * pl.col("n") / pl.col("n").filter(observed).sum()
),
)
.sort("gender", nulls_last=True)
)
gender_counts
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 4)
┌────────┬─────┬──────────────┬─────────────┐
│ gender ┆ n ┆ of_responses ┆ of_observed │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 ┆ f64 │
╞════════╪═════╪══════════════╪═════════════╡
│ Female ┆ 235 ┆ 46.719682 ┆ 47.0 │
│ Male ┆ 252 ┆ 50.099404 ┆ 50.4 │
│ Other ┆ 13 ┆ 2.584493 ┆ 2.6 │
│ null ┆ 3 ┆ 0.596421 ┆ null │
└────────┴─────┴──────────────┴─────────────┘
The null row represents three forms with the gender field blank. Including them gives 235/503, or about 46.7 percent, for Female. Among forms with a recorded gender, the share is 235/500, or 47 percent.
In add_margins(), sum().over("gender") gives the row total for each gender, and sum().over("region") gives the column total for each region. These totals are the margins. Each percentage uses its corresponding margin when that total is positive.
To represent combinations with no forms, cell_grid() cross-joins category values, pairing every gender with every region, then left-joins their counts. nulls_equal=True matches missing categories to their own counts because they are category labels in this table, not unknown identifiers. fill_null(0) assigns a zero to each combination with no responses.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def add_margins(cells):
return cells.with_columns(
row_total=pl.col("n").sum().over("gender"),
column_total=pl.col("n").sum().over("region"),
).with_columns(
row_percent=pl.when(pl.col("row_total") > 0).then(
100 * pl.col("n") / pl.col("row_total")
),
column_percent=pl.when(pl.col("column_total") > 0).then(
100 * pl.col("n") / pl.col("column_total")
),
)
def cell_grid(responses, gender_values, region_values):
counts = responses.group_by("gender", "region").agg(n=pl.len())
return (
gender_values.join(region_values, how="cross")
.join(
counts,
on=["gender", "region"],
how="left",
nulls_equal=True,
validate="1:1",
)
.with_columns(pl.col("n").fill_null(0))
)
five = pl.DataFrame(
{
"response": ["r1", "r2", "r3", "r4", "r5"],
"gender": ["Female", "Female", "Male", "Male", None],
"region": ["Seoul", "Busan", "Seoul", "Seoul", "Busan"],
}
)
five_cells = cell_grid(
five,
pl.DataFrame({"gender": ["Female", "Male", None]}),
pl.DataFrame({"region": ["Seoul", "Busan", "Jeju"]}),
)
add_margins(five_cells).sort("gender", "region", nulls_last=True)
responses_by_region = genders.select("gender", region=pl.col("Region"))
survey_cells = add_margins(
cell_grid(
responses_by_region,
responses_by_region.select(pl.col("gender").unique()),
responses_by_region.select(pl.col("region").unique()),
)
)
(survey_cells.height, (survey_cells["n"] == 0).sum(), survey_cells["n"].sum())
survey_cells.filter(
((pl.col("gender") == "Female") & (pl.col("region") == "Seoul"))
| ((pl.col("gender") == "Other") & (pl.col("region") == "Busan"))
| (pl.col("gender").is_null() & (pl.col("region") == "Busan"))
| ((pl.col("gender") == "Female") & pl.col("region").is_null())
).sort("gender", "region", nulls_last=True)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
shape: (9, 7)
┌────────┬────────┬─────┬───────────┬──────────────┬─────────────┬────────────────┐
│ gender ┆ region ┆ n ┆ row_total ┆ column_total ┆ row_percent ┆ column_percent │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 ┆ u32 ┆ u32 ┆ f64 ┆ f64 │
╞════════╪════════╪═════╪═══════════╪══════════════╪═════════════╪════════════════╡
│ Female ┆ Busan ┆ 1 ┆ 2 ┆ 2 ┆ 50.0 ┆ 50.0 │
│ Female ┆ Jeju ┆ 0 ┆ 2 ┆ 0 ┆ 0.0 ┆ null │
│ Female ┆ Seoul ┆ 1 ┆ 2 ┆ 3 ┆ 50.0 ┆ 33.333333 │
│ Male ┆ Busan ┆ 0 ┆ 2 ┆ 2 ┆ 0.0 ┆ 0.0 │
│ Male ┆ Jeju ┆ 0 ┆ 2 ┆ 0 ┆ 0.0 ┆ null │
│ Male ┆ Seoul ┆ 2 ┆ 2 ┆ 3 ┆ 100.0 ┆ 66.666667 │
│ null ┆ Busan ┆ 1 ┆ 1 ┆ 2 ┆ 100.0 ┆ 50.0 │
│ null ┆ Jeju ┆ 0 ┆ 1 ┆ 0 ┆ 0.0 ┆ null │
│ null ┆ Seoul ┆ 0 ┆ 1 ┆ 3 ┆ 0.0 ┆ 0.0 │
└────────┴────────┴─────┴───────────┴──────────────┴─────────────┴────────────────┘
(72, 29, 503)
shape: (4, 7)
┌────────┬────────┬─────┬───────────┬──────────────┬─────────────┬────────────────┐
│ gender ┆ region ┆ n ┆ row_total ┆ column_total ┆ row_percent ┆ column_percent │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 ┆ u32 ┆ u32 ┆ f64 ┆ f64 │
╞════════╪════════╪═════╪═══════════╪══════════════╪═════════════╪════════════════╡
│ Female ┆ Seoul ┆ 48 ┆ 235 ┆ 90 ┆ 20.425532 ┆ 53.333333 │
│ Female ┆ null ┆ 4 ┆ 235 ┆ 4 ┆ 1.702128 ┆ 100.0 │
│ Other ┆ Busan ┆ 0 ┆ 13 ┆ 27 ┆ 0.0 ┆ 0.0 │
│ null ┆ Busan ┆ 1 ┆ 3 ┆ 27 ┆ 33.333333 ┆ 3.703704 │
└────────┴────────┴─────┴───────────┴──────────────┴─────────────┴────────────────┘
Of the 235 forms that report Female, 48 report Seoul, or 20.4 percent. Of the 90 forms that report Seoul, the same 48 report Female, or 53.3 percent. The numerator is identical; the question determines which total belongs in the denominator.
The four forms marked Female with a blank region count toward the total of 235 and have their own cell in the missing-region column. No form reports both Other and Busan. One Busan form has no recorded gender. Thus a zero count, a missing category, and an undefined percentage represent different features of the data.
17.4 Comparing groups and comparing the same people
Changing the observations in a denominator changes the meaning of a percentage. The same issue arises when comparing means over time: do the means describe the same people? Table 17.2 shows the scores available for three people at two waves.
Table 17.2. Scores and changes in points for three people in a constructed panel.
| Person | Wave 1 | Wave 2 | Change |
|---|---|---|---|
| p1 | 2 | 4 | 2 |
| p2 | 8 | missing | unavailable |
| p3 | missing | 12 | unavailable |
At wave 1, p1 and p2 average 5 points. At wave 2, p1 and p3 average 8. The difference between those means is 3 points. Only p1 has both scores, and p1’s increase was 2 points, from 2 to 4. The difference between the available wave means therefore does not equal the observed change for the person measured twice.
A person with a score at only one wave still contributes to that wave’s mean. In R, pivot_longer() gives each person one row per wave, and names_prefix = "dep_" removes the prefix from the wave labels. After missing scores are excluded, the row count gives the number of people behind each mean. Sorting by wave makes diff() subtract the first mean from the second.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
panel <- read_csv(
"data/practice/panel_wide.csv",
col_types = cols(
dep_w1 = col_integer(),
dep_w2 = col_integer(),
.default = col_character()
),
na = "",
trim_ws = FALSE
)
wave_means <- panel |>
select(id, dep_w1, dep_w2) |>
pivot_longer(
c(dep_w1, dep_w2),
names_to = "wave",
names_prefix = "dep_",
values_to = "dep"
) |>
filter(!is.na(dep)) |>
summarise(n_people = n(), mean = mean(dep), ids = list(id), .by = wave) |>
arrange(wave)
wave_means
diff(wave_means$mean)
1
2
3
4
5
6
# A tibble: 2 × 4
wave n_people mean ids
<chr> <int> <dbl> <list>
1 w1 276 6.64 <chr [276]>
2 w2 259 6.76 <chr [259]>
[1] 0.1231744
Wave 1 has 276 observed totals and wave 2 has 259. The second mean is about 0.123 points higher. The expression ids = list(id) stores the identifiers for each wave. The printed tibble abbreviates them as <chr [276]> and <chr [259]>.
To measure change for one person, we need that person’s total at both waves. case_when() distinguishes people with both totals, wave 1 only, wave 2 only, or neither. Subtracting wave 1 from wave 2 gives a value only for the both group, so only that group contributes to mean change.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
pairs <- panel |>
select(id, dep_w1, dep_w2) |>
mutate(
status = case_when(
!is.na(dep_w1) & !is.na(dep_w2) ~ "both",
!is.na(dep_w1) ~ "wave 1 only",
!is.na(dep_w2) ~ "wave 2 only",
.default = "neither"
),
change = dep_w2 - dep_w1
)
count(pairs, status)
pairs |>
filter(status == "both") |>
summarise(
n_people = n(),
mean_w1 = mean(dep_w1),
mean_w2 = mean(dep_w2),
mean_change = mean(change)
)
1
2
3
4
5
6
7
8
9
10
11
# A tibble: 4 × 2
status n
<chr> <int>
1 both 225
2 neither 5
3 wave 1 only 51
4 wave 2 only 34
# A tibble: 1 × 4
n_people mean_w1 mean_w2 mean_change
<int> <dbl> <dbl> <dbl>
1 225 6.51 6.56 0.0489
Mean change is about 0.0489 points for the 225 people with both scores. Of the other 90 people, 51 have only a wave-1 score, 34 only a wave-2 score, and five have neither. For each of them, at least one of the two scores needed for subtraction is missing.
Each wave’s mean uses everyone with a score at that wave. In Polars, the two pl.Int64 totals become person/wave rows after unpivot(). With null totals removed, pl.len() gives the number of people behind each mean(), and pl.col("id").sort() records their identifiers. Sorting by wave fixes the order of subtraction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
panel = pl.read_csv(
"data/practice/panel_wide.csv",
infer_schema=False,
schema_overrides={"dep_w1": pl.Int64, "dep_w2": pl.Int64},
)
wave_means = (
panel.unpivot(
on=["dep_w1", "dep_w2"], index="id", variable_name="wave", value_name="dep"
)
.drop_nulls("dep")
.group_by("wave")
.agg(n_people=pl.len(), mean=pl.col("dep").mean(), ids=pl.col("id").sort())
.sort("wave")
)
wave_means
available_change = wave_means["mean"][1] - wave_means["mean"][0]
available_change
1
2
3
4
5
6
7
8
9
10
shape: (2, 4)
┌────────┬──────────┬──────────┬────────────────────────────┐
│ wave ┆ n_people ┆ mean ┆ ids │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 ┆ list[str] │
╞════════╪══════════╪══════════╪════════════════════════════╡
│ dep_w1 ┆ 276 ┆ 6.641304 ┆ ["0001", "0002", … "0300"] │
│ dep_w2 ┆ 259 ┆ 6.764479 ┆ ["0001", "0003", … "0315"] │
└────────┴──────────┴──────────┴────────────────────────────┘
0.12317441665267737
The available wave means differ by about 0.123 points, but they describe 276 and 259 people respectively. To measure each person’s change, we need to identify those with scores at both waves.
has_w1 and has_w2 test whether a person has a score at each wave, and the pl.when() chain distinguishes four cases. Subtraction gives a null change whenever either score is missing. The paired people row uses only people with both scores, so its two counts refer to exactly the same people.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
has_w1 = pl.col("dep_w1").is_not_null()
has_w2 = pl.col("dep_w2").is_not_null()
pairs = panel.select("id", "dep_w1", "dep_w2").with_columns(
status=pl.when(has_w1 & has_w2)
.then(pl.lit("both"))
.when(has_w1)
.then(pl.lit("wave 1 only"))
.when(has_w2)
.then(pl.lit("wave 2 only"))
.otherwise(pl.lit("neither")),
change=pl.col("dep_w2") - pl.col("dep_w1"),
)
pairs.group_by("status").agg(n=pl.len()).sort("status")
paired = pairs.filter(pl.col("status") == "both")
pl.DataFrame(
{
"comparison": ["available waves", "paired people"],
"people_w1": [wave_means["n_people"][0], paired.height],
"people_w2": [wave_means["n_people"][1], paired.height],
"change": [available_change, paired["change"].mean()],
}
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
shape: (4, 2)
┌─────────────┬─────┐
│ status ┆ n │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════════╪═════╡
│ both ┆ 225 │
│ neither ┆ 5 │
│ wave 1 only ┆ 51 │
│ wave 2 only ┆ 34 │
└─────────────┴─────┘
shape: (2, 4)
┌─────────────────┬───────────┬───────────┬──────────┐
│ comparison ┆ people_w1 ┆ people_w2 ┆ change │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ f64 │
╞═════════════════╪═══════════╪═══════════╪══════════╡
│ available waves ┆ 276 ┆ 259 ┆ 0.123174 │
│ paired people ┆ 225 ┆ 225 ┆ 0.048889 │
└─────────────────┴───────────┴───────────┴──────────┘
For the depression totals supplied in the file, the second-wave mean for 259 people is about 0.123 points higher than the first-wave mean for 276. That comparison includes 51 people with a score only at wave 1 and 34 with a score only at wave 2. Among the 225 people with both scores, the average increase is about 0.0489 points.
These results answer the chapter’s opening question: the increase in the available wave means differs from the mean change among people measured at both visits. The paired comparison describes those 225 people; it does not establish what the missing changes would have been for the others.
Weighting observations and people
The people included in a comparison are one part of its definition; their relative contributions are another. If we pool scores across visits, a person who contributes two scores has more weight in the mean than someone who contributes one. Suppose A contributes 2 and 4, while B contributes 10. In the pooled mean, each score receives one third of the total weight, so A accounts for two thirds. Averaging the two person means instead gives A and B equal weight.
1
2
3
4
5
repeated <- tibble(person = c("A", "A", "B"), value = c(2, 4, 10))
mean(repeated$value)
repeated |>
summarise(person_mean = mean(value), .by = person) |>
summarise(mean_of_people = mean(person_mean))
1
2
3
4
5
[1] 5.333333
# A tibble: 1 × 1
mean_of_people
<dbl>
1 6.5
1
2
3
4
5
repeated = pl.DataFrame({"person": ["A", "A", "B"], "value": [2, 4, 10]})
repeated["value"].mean()
repeated.group_by("person").agg(person_mean=pl.col("value").mean()).select(
mean_of_people=pl.col("person_mean").mean()
)
1
2
3
4
5
6
7
8
9
5.333333333333333
shape: (1, 1)
┌────────────────┐
│ mean_of_people │
│ --- │
│ f64 │
╞════════════════╡
│ 6.5 │
└────────────────┘
The observation mean is 16/3, about 5.33, with A contributing twice as many values as B. Averaging person means gives (3 + 10)/2 = 6.5, with equal weight for each person. The first describes the observed scores; the second describes the people’s average scores. As with the counts, percentages, and wave comparisons, interpreting the result requires stating which observations contribute and how they are counted.