Post

Nested Records and Multiple Selections

An app submission can group several answers inside a nested record, while one survey answer can list several selected activities. To compare mood ratings or count activity choices, we need to make those individual values accessible without losing the submission they came from. In this chapter, we first interpret the app’s record structure and extract its answers into columns. We then expand survey selections into rows and establish the denominator for a percentage of forms. Finally, we distinguish empty collections, missing collections, and missing entries, whose differences can disappear when their contents are expanded.

14.1 Reading the structure of a nested record

The momentary assessment app exported its submissions to data/raw/ema/ema_responses.json. Before counting submissions, we need to distinguish the response records from information about the export as a whole.

JSON (JavaScript Object Notation) is a text format for nested records, in which a value can itself be a record or a list. Curly braces enclose an object of named values, with a colon between each name and its value. Square brackets enclose an ordered array. Values may be text in double quotes, numbers, true, false, null, or further objects and arrays. These delimiters show where each submission begins and where its answers are nested.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "export_version": "2.1",
  "exported_at": "2024-06-17T03:00:00Z",
  "note": "synthetic data for teaching",
  "responses": [
    {
      "user_id": "E009",
      "submitted_at": "2024-04-01T00:31:32",
      "answers": {
        "mood": 3,
        "stress": 3,
        "energy": 6
      }
    },

The first submission begins just inside the responses array, with user_id equal to E009. The three fields before responses describe the export as a whole. Each object in the array records one submission, including its participant, submission time, and nested answers.

jsonlite::read_json() parses the file into R lists. The :: operator calls the function directly from jsonlite. With simplifyVector = FALSE, objects become named lists and arrays become unnamed lists. In the str() display, max.level = 1 limits the detail to the outer fields. A $ introduces a component name, and .. marks a deeper level.

1
2
3
4
5
6
7
8
library(tidyverse)

export <- jsonlite::read_json(
  "data/raw/ema/ema_responses.json",
  simplifyVector = FALSE
)
typeof(export)
str(export, max.level = 1)
1
2
3
4
5
6
[1] "list"
List of 4
 $ export_version: chr "2.1"
 $ exported_at   : chr "2024-06-17T03:00:00Z"
 $ note          : chr "synthetic data for teaching"
 $ responses     :List of 3323

The top level has four components, with 3,323 elements in responses. [[1]] retrieves the first submission, including its nested answers. There are no event IDs in the file, so seq_along() numbers submissions by source position.

Each submission also has a user_id, shown here for the first two. This identifies the participant rather than the submission. map_chr() from purrr collects those IDs in a character vector, and summing comparisons with "E009" counts how often that participant appears.

1
2
3
4
5
6
7
first <- export$responses[[1]]
names(first)
str(first)
event_ids <- seq_along(export$responses)
event_ids[c(1, 2, 3, 3323)]
export$responses[[2]]$user_id
sum(map_chr(export$responses, "user_id") == "E009")
1
2
3
4
5
6
7
8
9
10
11
[1] "user_id"      "submitted_at" "answers"     
List of 3
 $ user_id     : chr "E009"
 $ submitted_at: chr "2024-04-01T00:31:32"
 $ answers     :List of 3
  ..$ mood  : int 3
  ..$ stress: int 3
  ..$ energy: int 6
[1]    1    2    3 3323
[1] "E002"
[1] 51

Event 1 belongs to E009 and event 2 to E002. E009 appears in 51 submissions. Each has the same participant ID but a different position in this file.

In Python, the standard-library module json parses JSON objects into dictionaries and arrays into lists, using None for null and True or False for logical values. Path.read_text() reads the file as a string, and json.loads() parses that string. list(export) gives the outer field names, and type() identifies the container at each level.

1
2
3
4
5
6
7
8
9
10
import json
from pathlib import Path

import polars as pl

export_text = Path("data/raw/ema/ema_responses.json").read_text(encoding="utf-8")
export = json.loads(export_text)
type(export)
list(export)
type(export["responses"])
1
2
3
<class 'dict'>
['export_version', 'exported_at', 'note', 'responses']
<class 'list'>

export["responses"] is the list of submissions. responses[0] retrieves the first one, and first["answers"]["mood"] retrieves its mood answer. The comprehension uses enumerate(..., start=1) to pair each submission’s position in the file with its participant ID.

1
2
3
4
5
6
7
8
9
10
11
responses = export["responses"]
first = responses[0]
first
first["answers"]["mood"]
positions = [
    (event_id, record["user_id"])
    for event_id, record in enumerate(responses, start=1)
]
positions[:3]
positions[-1]
[record["user_id"] for record in responses].count("E009")
1
2
3
4
5
{'user_id': 'E009', 'submitted_at': '2024-04-01T00:31:32', 'answers': {'mood': 3, 'stress': 3, 'energy': 6}}
3
[(1, 'E009'), (2, 'E002'), (3, 'E001')]
(3323, 'E058')
51

The first submission belongs to E009, who appears 51 times. Numbering the submissions from 1 to 3,323 gives each one its own event ID within this file.

Event 1 has all three answers. Does event 76 have a mood field at all? In R, names(export$responses[[76]]$answers) lists its answer fields. In Python, the same event is responses[75], since list positions start at zero.

1
2
str(export$responses[[76]])
"mood" %in% names(export$responses[[76]]$answers)
1
2
3
4
5
6
7
List of 3
 $ user_id     : chr "E007"
 $ submitted_at: chr "2024-04-03T00:40:41"
 $ answers     :List of 2
  ..$ stress: int 2
  ..$ energy: int 5
[1] FALSE
1
2
responses[75]
"mood" in responses[75]["answers"]
1
2
{'user_id': 'E007', 'submitted_at': '2024-04-03T00:40:41', 'answers': {'stress': 2, 'energy': 5}}
False

Event 76 has stress 2 and energy 5 but no mood key. Its participant, E007, and its submission time are recorded. In this export, an omitted answer key marks an unanswered question, and the submission is present.

An omitted key is one way to represent a missing answer, but a value lookup alone may conceal other representations. Four constructed answer objects illustrate the distinction: one records mood 4, one omits mood, one gives mood the value null, and one is empty, written {}.

jsonlite::parse_json() reads JSON text. R’s $mood and Python’s record.get("mood") look up the value. If the lookup yields NULL or None, can we tell whether the original object contained the name mood?

1
2
3
4
5
6
7
8
9
miniature <- jsonlite::parse_json(
  '[{"mood": 4, "stress": 2}, {"stress": 2}, {"mood": null, "stress": 2}, {}]',
  simplifyVector = FALSE
)
str(miniature)
"mood" %in% names(miniature[[2]])
"mood" %in% names(miniature[[3]])
c(is.null(miniature[[2]]$mood), is.null(miniature[[3]]$mood))
length(miniature[[4]])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
List of 4
 $ :List of 2
  ..$ mood  : int 4
  ..$ stress: int 2
 $ :List of 1
  ..$ stress: int 2
 $ :List of 2
  ..$ mood  : NULL
  ..$ stress: int 2
 $ : Named list()
[1] FALSE
[1] TRUE
[1] TRUE TRUE
[1] 0
1
2
3
4
5
6
7
miniature = json.loads(
    '[{"mood": 4, "stress": 2}, {"stress": 2}, {"mood": null, "stress": 2}, {}]'
)
miniature
["mood" in record for record in miniature]
[record.get("mood") for record in miniature]
[len(record) for record in miniature]
1
2
3
4
[{'mood': 4, 'stress': 2}, {'stress': 2}, {'mood': None, 'stress': 2}, {}]
[True, False, True, False]
[4, None, None, None]
[2, 1, 2, 0]

Only the third object contains mood with an explicit null. The second omits mood but still contains stress. The fourth has no fields at all, so its length is zero. Looking up mood alone gives the same missing result in all three cases.

Counting submissions and missing answers

Which of these cases occur in the app export? For each submission, we count the expected names missing from answers and the fields that are present with a null value. We also count submissions whose answers object has no fields at all. A true condition adds one to its count. In Python, for name in answers visits only keys present in that submission, so an omitted field cannot count as an explicit null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
c(length(export), length(export$responses), length(event_ids))
expected_answers <- c("mood", "stress", "energy")
absent_fields <- 0L
explicit_nulls <- 0L
empty_answers <- 0L
for (record in export$responses) {
  answers <- record$answers
  absent_fields <- absent_fields + sum(!expected_answers %in% names(answers))
  empty_answers <- empty_answers + (length(answers) == 0)
  for (answer in answers) {
    explicit_nulls <- explicit_nulls + is.null(answer)
  }
}
c(absent_fields, explicit_nulls, empty_answers)
1
2
[1]    4 3323 3323
[1] 205   0   0
1
2
3
4
5
6
7
8
9
10
11
12
13
(len(export), len(responses), len(positions))
expected_answers = ["mood", "stress", "energy"]
absent_fields = 0
explicit_nulls = 0
empty_answers = 0
for record in responses:
    answers = record["answers"]
    absent_fields = absent_fields + sum([name not in answers for name in expected_answers])
    empty_answers = empty_answers + (len(answers) == 0)
    for name in answers:
        explicit_nulls = explicit_nulls + (answers[name] is None)

(absent_fields, explicit_nulls, empty_answers)
1
2
(4, 3323, 3323)
(205, 0, 0)

The outer object has four fields, and its responses array contains 3,323 submissions. Across those submissions, 205 expected answer fields are absent. A submission can lack more than one answer. No answer is explicitly null, and no answers object is empty.

14.2 Flattening records while preserving their identity

To analyze mood, stress and energy across submissions, we need each question’s answers in a column. Flattening turns the 3,323 parsed submissions into that table, with one row per event. The event_id, user_id and recorded submitted_at text identify which submission each set of answers describes. Even without a mood key, event 76 needs a row for its stress and energy answers.

The tibble pairs each event ID with its response in the record list column. tidyr::unnest_wider() creates columns for names found anywhere in the input and fills absent components with NA. Widening record gives us user_id, submitted_at, and answers. Widening answers gives each question its own column.

1
2
3
4
5
6
7
event_records <- tibble(event_id = event_ids, record = export$responses)
print(event_records, n = 3)
events <- event_records |>
  unnest_wider(record) |>
  unnest_wider(answers)
print(events, n = 3)
filter(events, event_id == 76)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# A tibble: 3,323 × 2
  event_id record          
     <int> <list>          
1        1 <named list [3]>
2        2 <named list [3]>
3        3 <named list [3]>
# ℹ 3,320 more rows
# ℹ Use `print(n = ...)` to see more rows
# A tibble: 3,323 × 6
  event_id user_id submitted_at         mood stress energy
     <int> <chr>   <chr>               <int>  <int>  <int>
1        1 E009    2024-04-01T00:31:32     3      3      6
2        2 E002    2024-04-01T00:39:08     6      5      3
3        3 E001    2024-04-01T00:48:24     3      4      6
# ℹ 3,320 more rows
# ℹ Use `print(n = ...)` to see more rows
# A tibble: 1 × 6
  event_id user_id submitted_at         mood stress energy
     <int> <chr>   <chr>               <int>  <int>  <int>
1       76 E007    2024-04-03T00:40:41    NA      2      5

Event 76 has NA for mood, stress 2, and energy 5. Across all events, the IDs should match the original positions in order, and the missing cells should account for the 205 absent fields.

1
2
3
4
5
6
7
c(nrow(events), length(export$responses), n_distinct(events$event_id))
identical(events$event_id, event_ids)
c(
  mood = sum(is.na(events$mood)),
  stress = sum(is.na(events$stress)),
  energy = sum(is.na(events$energy))
)
1
2
3
4
[1] 3323 3323 3323
[1] TRUE
  mood stress energy 
    68     60     77 

All 3,323 event IDs match their original positions in order. The 68 missing mood values, 60 missing stress values, and 77 missing energy values account for all 205 omitted answers.

In Polars, pl.DataFrame() takes one response dictionary per row. The schema gives user_id and submitted_at text fields. For answers, it specifies a struct, a column whose cells have the same named fields. Here those fields are three integers, and an absent key becomes null.

with_row_index(..., offset=1) numbers events by their source positions. unnest("answers") then places each answer field in its own column without changing the event represented by a row.

1
2
3
4
5
6
7
8
9
10
11
answer_fields = pl.Struct({"mood": pl.Int64, "stress": pl.Int64, "energy": pl.Int64})
event_schema = {
    "user_id": pl.String,
    "submitted_at": pl.String,
    "answers": answer_fields,
}
event_records = pl.DataFrame(responses, schema=event_schema).with_row_index(
    "event_id", offset=1
)
event_records.head(3)
events = event_records.unnest("answers")
1
2
3
4
5
6
7
8
9
10
shape: (3, 4)
┌──────────┬─────────┬─────────────────────┬───────────┐
│ event_id ┆ user_id ┆ submitted_at        ┆ answers   │
│ ---      ┆ ---     ┆ ---                 ┆ ---       │
│ u32      ┆ str     ┆ str                 ┆ struct[3] │
╞══════════╪═════════╪═════════════════════╪═══════════╡
│ 1        ┆ E009    ┆ 2024-04-01T00:31:32 ┆ {3,3,6}   │
│ 2        ┆ E002    ┆ 2024-04-01T00:39:08 ┆ {6,5,3}   │
│ 3        ┆ E001    ┆ 2024-04-01T00:48:24 ┆ {3,4,6}   │
└──────────┴─────────┴─────────────────────┴───────────┘

In the first answers cell, {3,3,6} gives mood, stress, and energy in schema order. After unnesting, do the event IDs still match their source positions? The next output counts missing answers by question and shows the row for event 76.

1
2
3
4
(events.height, len(responses), events["event_id"].n_unique())
events["event_id"].to_list() == [pair[0] for pair in positions]
events.select(pl.col("mood", "stress", "energy").null_count())
events.filter(pl.col("event_id") == 76)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
(3323, 3323, 3323)
True
shape: (1, 3)
┌──────┬────────┬────────┐
│ mood ┆ stress ┆ energy │
│ ---  ┆ ---    ┆ ---    │
│ u32  ┆ u32    ┆ u32    │
╞══════╪════════╪════════╡
│ 68   ┆ 60     ┆ 77     │
└──────┴────────┴────────┘
shape: (1, 6)
┌──────────┬─────────┬─────────────────────┬──────┬────────┬────────┐
│ event_id ┆ user_id ┆ submitted_at        ┆ mood ┆ stress ┆ energy │
│ ---      ┆ ---     ┆ ---                 ┆ ---  ┆ ---    ┆ ---    │
│ u32      ┆ str     ┆ str                 ┆ i64  ┆ i64    ┆ i64    │
╞══════════╪═════════╪═════════════════════╪══════╪════════╪════════╡
│ 76       ┆ E007    ┆ 2024-04-03T00:40:41 ┆ null ┆ 2      ┆ 5      │
└──────────┴─────────┴─────────────────────┴──────┴────────┴────────┘

The IDs match in source order, and all 3,323 are distinct. Event 76 has its participant and time, a null mood, stress 2, and energy 5. The column null counts total 205, accounting for the absent source fields.

Comparing with the practice file

If the flattening is correct, the table should agree with the practice file data/practice/ema_responses.csv. That file contains these responses in the same source order, with blank cells for missing answers and no event ID. Their shared order lets us compare row 76 and then every field without an ID. The CSV values are read as text, so as.character() in R and cast(pl.String) in Polars give the extracted answers the same representation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
practice <- read_csv(
  "data/practice/ema_responses.csv",
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
practice[76, ]
c(
  rows = nrow(practice) == nrow(events),
  user_id = identical(practice$user_id, events$user_id),
  submitted_at = identical(practice$submitted_at, events$submitted_at),
  mood = identical(practice$mood, as.character(events$mood)),
  stress = identical(practice$stress, as.character(events$stress)),
  energy = identical(practice$energy, as.character(events$energy))
)
1
2
3
4
5
6
# A tibble: 1 × 5
  user_id submitted_at        mood  stress energy
  <chr>   <chr>               <chr> <chr>  <chr> 
1 E007    2024-04-03T00:40:41 <NA>  2      5     
        rows      user_id submitted_at         mood       stress       energy 
        TRUE         TRUE         TRUE         TRUE         TRUE         TRUE 
1
2
3
4
5
6
7
8
9
practice = pl.read_csv("data/practice/ema_responses.csv", infer_schema=False)
practice.row(75)
answer_names = ["mood", "stress", "energy"]
(
    practice.height == events.height,
    practice["user_id"].equals(events["user_id"]),
    practice["submitted_at"].equals(events["submitted_at"]),
    [practice[name].equals(events[name].cast(pl.String)) for name in answer_names],
)
1
2
('E007', '2024-04-03T00:40:41', None, '2', '5')
(True, True, True, [True, True, True])

For all 3,323 submissions, the participant, recorded time, and three answers agree row by row. In particular, the blank mood cell in CSV row 76 corresponds to the omitted mood key in the JSON.

The same answers stored as text

The practice file stores answers in separate columns, but another export could store the same answers as JSON text in one cell. Beside event ID 76, that cell could contain {"stress":2,"energy":5}. Extracting this one record raises a question that the full export did not: how do we create a mood column when none of the supplied records has a mood key?

purrr::map() applies jsonlite::fromJSON() to each answers_json string and collects the parsed records in a list column. In this one-row example, unnest_wider() would find only stress and energy. tidyr::hoist() lets us request mood by name as well. Its .ptype argument gives the new columns integer types, including the NA in the requested mood column.

1
2
3
4
5
6
7
8
9
answer_text <- tibble(event_id = 76L, answers_json = '{"stress":2,"energy":5}')
selected_answers <- answer_text |>
  mutate(answers = map(answers_json, jsonlite::fromJSON)) |>
  hoist(
    answers,
    mood = "mood", stress = "stress", energy = "energy",
    .ptype = list(mood = integer(), stress = integer(), energy = integer())
  )
select(selected_answers, event_id, mood, stress, energy)
1
2
3
4
# A tibble: 1 × 4
  event_id  mood stress energy
     <int> <int>  <int>  <int>
1       76    NA      2      5

In Polars, str.json_decode() turns the JSON string into a struct. dtype=answer_fields requests all three integer fields, including absent mood, and unnest() makes them ordinary columns.

1
2
3
4
5
answer_text = pl.DataFrame({"event_id": [76], "answers_json": ['{"stress":2,"energy":5}']})
selected_answers = answer_text.with_columns(
    answers=pl.col("answers_json").str.json_decode(dtype=answer_fields)
).unnest("answers")
selected_answers.select("event_id", "mood", "stress", "energy").rows()
1
[(76, None, 2, 5)]

Both extractions give event 76 a missing mood, stress 2, and energy 5, the same values as its nested record. Whether the answers arrive as a nested object or as JSON text in a cell, the event occupies one row.

14.3 Expanding multiple selections and defining a denominator

The nested app answers became separate columns in one row per submission. Multiple selections require a different arrangement: one form may name several activities, each of which we want to count. The survey’s Q_MULTI question asks which activities respondents use to reduce stress. On one form, participant 0034 marked exercise, getting enough sleep, and playing games. The recorded answer, 1;3;5, represents three choices from one form. What percentage of the forms with an answer to this question included exercise?

A blank means the question went unanswered; after splitting, that form is represented by one row with a missing option. Code 8 means “None of the above.” It counts as an answer, and the survey requires it to appear alone.

ResponseId identifies the form, ID the participant, and Q_MULTI records the original answer. tidyr::separate_longer_delim() splits a copy named option at each semicolon. Each choice becomes a row with the form’s identifiers and original text. A blank answer produces one row with NA in option.

1
2
3
4
5
6
7
8
9
10
11
12
survey <- read_csv(
  "data/practice/survey.csv",
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
choices <- survey |>
  select(ResponseId, ID, Q_MULTI) |>
  mutate(option = Q_MULTI) |>
  separate_longer_delim(option, delim = ";")
focal_ids <- c("R_nMxPhW4zivOi", "R_OcVHP34kFUAU", "R_M9X7Sbo4BGCU")
filter(choices, ResponseId %in% focal_ids)
1
2
3
4
5
6
7
8
# A tibble: 5 × 4
  ResponseId     ID    Q_MULTI option
  <chr>          <chr> <chr>   <chr> 
1 R_M9X7Sbo4BGCU 0361  8       8     
2 R_nMxPhW4zivOi 0034  1;3;5   1     
3 R_nMxPhW4zivOi 0034  1;3;5   3     
4 R_nMxPhW4zivOi 0034  1;3;5   5     
5 R_OcVHP34kFUAU 0163  <NA>    <NA>  

The three rows for 1;3;5 share one response ID and the original answer. Code 8 and the blank have one row each, one with an observed option and one with a missing option.

The dictionary option_labels pairs each of the eight codes with its meaning. The join matches each code to its count in the expanded table. For the denominator, answered counts nonblank Q_MULTI answers in survey, where each form appears once. An option count gives the number of forms that chose it only if no form lists that option twice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
option_labels <- tibble(
  option = c("1", "2", "3", "4", "5", "6", "7", "8"),
  label = c(
    "Exercise", "Listening to music", "Enough sleep", "Talking with someone",
    "Games", "Good food", "Other", "None of the above"
  )
)
answered <- sum(!is.na(survey$Q_MULTI))
answered
option_counts <- option_labels |>
  left_join(
    count(filter(choices, !is.na(option)), option),
    by = join_by(option),
    relationship = "one-to-one"
  ) |>
  mutate(percent = 100 * n / answered)
option_counts
1
2
3
4
5
6
7
8
9
10
11
12
[1] 492
# A tibble: 8 × 4
  option label                    n percent
  <chr>  <chr>                <int>   <dbl>
1 1      Exercise               176   35.8 
2 2      Listening to music     223   45.3 
3 3      Enough sleep           200   40.7 
4 4      Talking with someone   203   41.3 
5 5      Games                  107   21.7 
6 6      Good food              146   29.7 
7 7      Other                   31    6.30
8 8      None of the above       10    2.03

In Polars, str.split(";") turns the codes in Q_MULTI into a list named option. explode() gives each list element a row with the form’s identifiers and original answer. A blank answer produces a null list, and keep_nulls=True gives it one row with a null option.

1
2
3
4
5
6
7
8
survey = pl.read_csv("data/practice/survey.csv", infer_schema=False)
choices = (
    survey.select("ResponseId", "ID", "Q_MULTI")
    .with_columns(option=pl.col("Q_MULTI").str.split(";"))
    .explode("option", keep_nulls=True)
)
focal_ids = ["R_nMxPhW4zivOi", "R_OcVHP34kFUAU", "R_M9X7Sbo4BGCU"]
choices.filter(pl.col("ResponseId").is_in(focal_ids))
1
2
3
4
5
6
7
8
9
10
11
12
shape: (5, 4)
┌────────────────┬──────┬─────────┬────────┐
│ ResponseId     ┆ ID   ┆ Q_MULTI ┆ option │
│ ---            ┆ ---  ┆ ---     ┆ ---    │
│ str            ┆ str  ┆ str     ┆ str    │
╞════════════════╪══════╪═════════╪════════╡
│ R_M9X7Sbo4BGCU ┆ 0361 ┆ 8       ┆ 8      │
│ R_nMxPhW4zivOi ┆ 0034 ┆ 1;3;5   ┆ 1      │
│ R_nMxPhW4zivOi ┆ 0034 ┆ 1;3;5   ┆ 3      │
│ R_nMxPhW4zivOi ┆ 0034 ┆ 1;3;5   ┆ 5      │
│ R_OcVHP34kFUAU ┆ 0163 ┆ null    ┆ null   │
└────────────────┴──────┴─────────┴────────┘

The 1;3;5 response now occupies three rows, each with the same response ID and original text. The blank is one row, with a null option, while code 8 is an observed selection.

In survey, a form counts once toward answered if Q_MULTI has an answer. In choices, each occurrence of an activity adds one to its count. If no form repeats the same activity, this is also the number of forms that mention it. The join uses validate="1:1" to pair each option count with its label.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
option_labels = pl.DataFrame(
    {
        "option": ["1", "2", "3", "4", "5", "6", "7", "8"],
        "label": [
            "Exercise",
            "Listening to music",
            "Enough sleep",
            "Talking with someone",
            "Games",
            "Good food",
            "Other",
            "None of the above",
        ],
    }
)
answered = survey["Q_MULTI"].drop_nulls().len()
answered
selection_counts = choices.drop_nulls("option").group_by("option").agg(n=pl.len())
option_counts = (
    option_labels.join(selection_counts, on="option", how="left", validate="1:1")
    .with_columns(percent=100 * pl.col("n") / answered)
    .sort("option")
)
option_counts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
492
shape: (8, 4)
┌────────┬──────────────────────┬─────┬───────────┐
│ option ┆ label                ┆ n   ┆ percent   │
│ ---    ┆ ---                  ┆ --- ┆ ---       │
│ str    ┆ str                  ┆ u32 ┆ f64       │
╞════════╪══════════════════════╪═════╪═══════════╡
│ 1      ┆ Exercise             ┆ 176 ┆ 35.772358 │
│ 2      ┆ Listening to music   ┆ 223 ┆ 45.325203 │
│ 3      ┆ Enough sleep         ┆ 200 ┆ 40.650407 │
│ 4      ┆ Talking with someone ┆ 203 ┆ 41.260163 │
│ 5      ┆ Games                ┆ 107 ┆ 21.747967 │
│ 6      ┆ Good food            ┆ 146 ┆ 29.674797 │
│ 7      ┆ Other                ┆ 31  ┆ 6.300813  │
│ 8      ┆ None of the above    ┆ 10  ┆ 2.03252   │
└────────┴──────────────────────┴─────┴───────────┘

An expanded row can contain a selection or stand in for a blank answer. Distinct ResponseId values count forms, and distinct ID values count people. If one form listed exercise twice, its two rows would count twice for exercise. The checks look for repeated (ResponseId, option) pairs and for forms that combine code 8 with another choice.

1
2
3
4
5
6
7
8
9
10
11
12
13
c(
  expanded_rows = nrow(choices),
  blank_rows = sum(is.na(choices$option)),
  selections = sum(option_counts$n),
  responses = nrow(survey),
  expanded_responses = n_distinct(choices$ResponseId),
  answered = answered,
  participants = n_distinct(survey$ID)
)
c(
  repeated_options = nrow(choices) - n_distinct(choices$ResponseId, choices$option),
  mixed_none = sum(choices$option == "8" & choices$Q_MULTI != "8", na.rm = TRUE)
)
1
2
3
4
5
6
     expanded_rows         blank_rows         selections          responses 
              1107                 11               1096                503 
expanded_responses           answered       participants 
               503                492                500 
repeated_options       mixed_none 
               0                0 
1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "expanded_rows": choices.height,
    "blank_rows": choices["option"].null_count(),
    "selections": option_counts["n"].sum(),
    "responses": survey.height,
    "expanded_responses": choices["ResponseId"].n_unique(),
    "answered": answered,
    "participants": survey["ID"].n_unique(),
}
(
    choices.height - choices.select("ResponseId", "option").n_unique(),
    ((choices["option"] == "8") & (choices["Q_MULTI"] != "8")).sum(),
)
1
2
{'expanded_rows': 1107, 'blank_rows': 11, 'selections': 1096, 'responses': 503, 'expanded_responses': 503, 'answered': 492, 'participants': 500}
(0, 0)

All 503 forms are still present after splitting. Their 1,107 rows consist of 1,096 selections and 11 placeholders for blanks. No form repeats an option, and every form with code 8 lists it alone. Each activity’s count therefore tells us how many forms mentioned it. The 503 forms came from 500 people because some people submitted more than once.

Exercise appears on 176 of the 492 forms with an answer, or 35.8 percent. The 10 forms marked “None of the above” also count among the 492. Music appears on 223 forms, or 45.3 percent. Those same 223 choices account for 20.3 percent of all 1,096 selections. A form can count toward several activities, so the percentages of forms in the table add up to about 223 percent.

14.4 Working with collections inside a column

The expanded survey table contains rows for selections and rows for unanswered questions. More general list data can produce a blank entry for another reason: a known collection may have no elements. To distinguish these cases after expansion, we record each list’s size and the number of observed values beforehand.

In this constructed table, each list belongs to one row, its parent. The list for p1 contains 1 and 3. For p2, the list is empty. For p3, the list itself is unrecorded, so its size is unknown. For p4, one entry exists but its value is missing. None of these cases should be confused with the survey’s “None of the above,” which records one known value, code 8.

An R list column can represent all four collections. integer(0) represents the known empty collection, NULL the unknown collection, and NA_integer_ the one missing entry. The tibble displays each cell in abbreviated form, while str() shows its contents.

1
2
3
4
5
6
parents <- tibble(
  parent = c("p1", "p2", "p3", "p4"),
  entries = list(c(1L, 3L), integer(0), NULL, NA_integer_)
)
parents
str(parents$entries)
1
2
3
4
5
6
7
8
9
10
11
12
# A tibble: 4 × 2
  parent entries  
  <chr>  <list>   
1 p1     <int [2]>
2 p2     <int [0]>
3 p3     <NULL>   
4 p4     <int [1]>
List of 4
 $ : int [1:2] 1 3
 $ : int(0) 
 $ : NULL
 $ : int NA

For p4, <int [1]> means one integer entry. In str(), that entry appears as int NA. lengths() counts the entries in each cell. map_lgl(parents$entries, is.null) tests each cell and returns a logical vector identifying the unknown collections.

1
2
lengths(parents$entries)
map_lgl(parents$entries, is.null)
1
2
[1] 2 0 0 1
[1] FALSE FALSE  TRUE FALSE

lengths() gives 0 for both p2 and p3 because length(NULL) is zero. Only p2 has a known size of zero. To count observed entries, map_int() applies \(x) sum(!is.na(x)) to each list, where \(x) is shorthand for function(x). When known is false, if_else() records NA for both counts.

1
2
3
4
5
6
7
counted <- parents |>
  mutate(
    known = !map_lgl(entries, is.null),
    n_entries = if_else(known, lengths(entries), NA_integer_),
    n_observed = if_else(known, map_int(entries, \(x) sum(!is.na(x))), NA_integer_)
  )
counted
1
2
3
4
5
6
7
# A tibble: 4 × 5
  parent entries   known n_entries n_observed
  <chr>  <list>    <lgl>     <int>      <int>
1 p1     <int [2]> TRUE          2          2
2 p2     <int [0]> TRUE          0          0
3 p3     <NULL>    FALSE        NA         NA
4 p4     <int [1]> TRUE          1          0

Both counts are NA for p3, whose list is unrecorded. The lists for p2 and p4 both have zero observed values, but only p4 has an entry.

The Polars column entries has type pl.List(pl.Int64). In the Python input, [] represents an empty collection, None an unknown collection, and [None] one missing entry. to_list() shows those Python representations beside the DataFrame display.

1
2
3
4
5
6
parents = pl.DataFrame(
    {"parent": ["p1", "p2", "p3", "p4"], "entries": [[1, 3], [], None, [None]]},
    schema={"parent": pl.String, "entries": pl.List(pl.Int64)},
)
parents
parents["entries"].to_list()
1
2
3
4
5
6
7
8
9
10
11
12
shape: (4, 2)
┌────────┬───────────┐
│ parent ┆ entries   │
│ ---    ┆ ---       │
│ str    ┆ list[i64] │
╞════════╪═══════════╡
│ p1     ┆ [1, 3]    │
│ p2     ┆ []        │
│ p3     ┆ null      │
│ p4     ┆ [null]    │
└────────┴───────────┘
[[1, 3], [], None, [None]]

The display distinguishes a null cell from [null], a list containing a null element. In counted, is_not_null() marks known collections and list.len() counts their entries, returning null for an unknown collection. The length after list.drop_nulls() counts just the observed entries in each list.

1
2
3
4
5
6
counted = parents.with_columns(
    known=pl.col("entries").is_not_null(),
    n_entries=pl.col("entries").list.len(),
    n_observed=pl.col("entries").list.drop_nulls().list.len(),
)
counted
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 5)
┌────────┬───────────┬───────┬───────────┬────────────┐
│ parent ┆ entries   ┆ known ┆ n_entries ┆ n_observed │
│ ---    ┆ ---       ┆ ---   ┆ ---       ┆ ---        │
│ str    ┆ list[i64] ┆ bool  ┆ u32       ┆ u32        │
╞════════╪═══════════╪═══════╪═══════════╪════════════╡
│ p1     ┆ [1, 3]    ┆ true  ┆ 2         ┆ 2          │
│ p2     ┆ []        ┆ true  ┆ 0         ┆ 0          │
│ p3     ┆ null      ┆ false ┆ null      ┆ null       │
│ p4     ┆ [null]    ┆ true  ┆ 1         ┆ 0          │
└────────┴───────────┴───────┴───────────┴────────────┘

For p2, both counts are 0. For p3, both are null. For p4, the list has one entry and zero observed values.

Expanding these lists tests whether the result still distinguishes all four parents. tidyr::unnest_longer() gives each list element a row. The empty list for p2 and the unrecorded list for p3 have no recorded elements to expand. With keep_empty = TRUE, each produces a row with NA in entries.

1
2
3
4
unnest_longer(parents, entries)
expanded <- unnest_longer(counted, entries, keep_empty = TRUE)
expanded
n_distinct(expanded$parent)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# A tibble: 3 × 2
  parent entries
  <chr>    <int>
1 p1           1
2 p1           3
3 p4          NA
# A tibble: 5 × 5
  parent entries known n_entries n_observed
  <chr>    <int> <lgl>     <int>      <int>
1 p1           1 TRUE          2          2
2 p1           3 TRUE          2          2
3 p2          NA TRUE          0          0
4 p3          NA FALSE        NA         NA
5 p4          NA TRUE          1          0
[1] 4

The default result includes p4, whose list contains one missing value, but omits p2 and p3. With keep_empty = TRUE, all four parents appear. Beside the three NA entries, n_entries shows 0 for p2, NA for p3, and 1 for p4.

In Polars, explode() treats a null collection and an empty list separately. The default keep_nulls=True gives a null collection one row. With empty_as_null=True, an empty list also gives one row with a null entry. Each row in expanded includes the counts calculated before expansion.

1
2
3
4
parents.explode("entries")
expanded = counted.explode("entries", empty_as_null=True)
expanded
expanded["parent"].n_unique()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
shape: (4, 2)
┌────────┬─────────┐
│ parent ┆ entries │
│ ---    ┆ ---     │
│ str    ┆ i64     │
╞════════╪═════════╡
│ p1     ┆ 1       │
│ p1     ┆ 3       │
│ p3     ┆ null    │
│ p4     ┆ null    │
└────────┴─────────┘
shape: (5, 5)
┌────────┬─────────┬───────┬───────────┬────────────┐
│ parent ┆ entries ┆ known ┆ n_entries ┆ n_observed │
│ ---    ┆ ---     ┆ ---   ┆ ---       ┆ ---        │
│ str    ┆ i64     ┆ bool  ┆ u32       ┆ u32        │
╞════════╪═════════╪═══════╪═══════════╪════════════╡
│ p1     ┆ 1       ┆ true  ┆ 2         ┆ 2          │
│ p1     ┆ 3       ┆ true  ┆ 2         ┆ 2          │
│ p2     ┆ null    ┆ true  ┆ 0         ┆ 0          │
│ p3     ┆ null    ┆ false ┆ null      ┆ null       │
│ p4     ┆ null    ┆ true  ┆ 1         ┆ 0          │
└────────┴─────────┴───────┴───────────┴────────────┘
4

The default Polars result includes p3 and drops p2. With empty_as_null=True, all four parents appear. The three nulls in entries look alike. Beside them, n_entries is 0 for p2’s empty list, null for p3’s unrecorded list, and 1 for p4’s single missing entry.

With one row per parent, n_entries gives the size of each known list. In the expanded table, you can count individual values across lists. The value 3 occurs once, in a row for p1. Of the three rows with a missing value in entries, only the row for p4 represents an entry in the original list.

This post is licensed under CC BY-NC 4.0 by the author.