Post

Text as Characters, Patterns, and Categories

Before grouping text answers or matching records by name, we need to decide which differences in their recorded text matter. Two strings can look identical yet compare unequal, while an abbreviation and a full label can describe the same survey category. Character comparison alone cannot resolve both problems. We begin by examining character representations, then use explicit mappings to reconcile labels according to the survey’s definitions. The chapter also shows how to extract structured information from text and organize categories in an order defined by the questionnaire rather than by spelling.

9.1 Characters, encoding, and Unicode representation

Two strings can display as café yet contain different characters. The difference lies in how the accent is written, and it changes whether the strings compare equal.

Unicode assigns each character a number called a code point. In these R strings, \u00e9 writes é and \u0301 writes a combining acute accent. The digits after \u are hexadecimal. utf8ToInt() displays the code points as decimal numbers, and nchar() counts the characters in each string.

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

composed <- "caf\u00e9"
decomposed <- "cafe\u0301"
composed
decomposed
composed == decomposed
nchar(composed)
nchar(decomposed)
utf8ToInt(composed)
utf8ToInt(decomposed)
1
2
3
4
5
6
7
[1] "café"
[1] "café"
[1] FALSE
[1] 4
[1] 5
[1]  99  97 102 233
[1]  99  97 102 101 769

The first three code points spell caf in both strings. One string ends in code point 233, U+00E9, for é. The other ends in 101 and 769, a plain e followed by a combining accent. That extra code point explains why nchar() gives 4 and 5 for strings that look alike. Both are valid decoded text, so changing the file encoding would not make them equal.

Unicode treats these two spellings as canonically equivalent, meaning that they represent the same text. Normalization Form C (NFC) gives such strings the same sequence of code points. Here, it combines e and its accent into é. stringi::stri_trans_nfc() applies NFC. The :: names stringi explicitly because loading tidyverse does not attach that package.

1
2
3
4
nfc_decomposed <- stringi::stri_trans_nfc(decomposed)
utf8ToInt(nfc_decomposed)
nfc_decomposed == composed
stringi::stri_trans_nfc(composed) == composed
1
2
3
[1]  99  97 102 233
[1] TRUE
[1] TRUE

The normalized sequence now ends in 233 and equals the composed form. The already-composed string is unchanged. NFC changes the representation and does not correct spelling, so it would not add an accent to cafe.

Each row of data/practice/survey.csv is one submitted questionnaire. Two of the three Q_OPEN answers selected by ResponseId look like “Made a to-do list.” With trim_ws = FALSE, readr::read_csv() includes any spaces at the ends of fields. The spaces of interest are between words. ASCII includes ordinary spaces and unaccented English letters. stringi::stri_escape_unicode() displays characters outside ASCII as escapes, and writeLines() prints one answer per line.

1
2
3
4
5
6
7
8
9
10
11
12
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")
)
selected_ids <- c("R_GVb9r7EyNijP", "R_oA7M9tOjykZC", "R_asHQHy90yidr")
selected <- filter(survey, ResponseId %in% selected_ids)
selected$ResponseId
selected$Q_OPEN
writeLines(stringi::stri_escape_unicode(selected$Q_OPEN))
1
2
3
4
5
[1] "R_GVb9r7EyNijP" "R_oA7M9tOjykZC" "R_asHQHy90yidr"
[1] "Made a to-do list." "Made a to-do list." "Watched a movie." 
Made a to-do list.
Made\u00a0a to-do list.
Watched\u3000a movie.

The first answer uses ordinary spaces. The second has a no-break space, U+00A0, after Made, and the third has the wider ideographic space U+3000 after Watched. The escapes name the characters that the display can hide.

For this comparison of open answers, we treat the two special spaces as word separators equivalent to an ordinary space. This is an additional replacement rule, beyond NFC.

For each recorded answer in Q_OPEN, open_nfc gives its NFC form. In open_repaired, stringr::str_replace_all() replaces U+00A0 and U+3000 with ordinary spaces. Its named vector pairs each target with its replacement. The bracketed pattern in str_detect() tests for either space, so an answer with several matches still counts only once. The sums omit missing answers with na.rm = TRUE.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
open_answers <- survey |>
  select(ResponseId, Q_OPEN) |>
  mutate(
    open_nfc = stringi::stri_trans_nfc(Q_OPEN),
    open_repaired = str_replace_all(open_nfc, c("\u00a0" = " ", "\u3000" = " "))
  )
c(
  sum(open_answers$open_nfc != open_answers$Q_OPEN, na.rm = TRUE),
  sum(str_detect(open_answers$open_nfc, "[\u00a0\u3000]"), na.rm = TRUE),
  sum(str_detect(open_answers$open_repaired, "[\u00a0\u3000]"), na.rm = TRUE),
  sum(open_answers$open_repaired != open_answers$Q_OPEN, na.rm = TRUE)
)
repaired_selected <- filter(open_answers, ResponseId %in% selected_ids)
writeLines(stringi::stri_escape_unicode(repaired_selected$open_repaired))
repaired_selected$open_repaired[1] == repaired_selected$open_repaired[2]
1
2
3
4
5
[1]  4  6  0 10
Made a to-do list.
Made a to-do list.
Watched a movie.
[1] TRUE

NFC changed four answers. Six others contained a no-break or ideographic space even after NFC. Replacing those spaces brought the total to ten changed answers. The first two selected answers now match in open_repaired. Their original spacing is visible in the escaped Q_OPEN output.

A Unicode code point is the number assigned to a character. In a Python string, \u followed by four hexadecimal digits writes that character. One spelling of café ends in é. The other ends in e followed by a combining accent, \u0301. The comprehension uses ord() to list the code points.

Unicode treats the two sequences as canonically equivalent: they represent the same text. Normalization Form C (NFC) gives canonically equivalent strings the same sequence of code points. The standard library’s unicodedata.normalize("NFC", decomposed) applies that rule to the second spelling.

1
2
3
4
5
6
7
8
9
10
11
12
import polars as pl
import unicodedata

composed = "caf\u00e9"
decomposed = "cafe\u0301"
composed, decomposed
composed == decomposed
[ord(character) for character in composed]
[ord(character) for character in decomposed]
nfc_decomposed = unicodedata.normalize("NFC", decomposed)
[ord(character) for character in nfc_decomposed]
nfc_decomposed == composed
1
2
3
4
5
6
('café', 'café')
False
[99, 97, 102, 233]
[99, 97, 102, 101, 769]
[99, 97, 102, 233]
True

The original endings are 233 for é and 101, 769 for e followed by its accent. NFC combines the latter pair into code point 233, so the strings now compare equal. Both original strings were valid decoded text; normalization resolves their different representations rather than correcting a file encoding.

In data/practice/survey.csv, each row is one submitted questionnaire. Two of the three Q_OPEN answers selected by ResponseId look like “Made a to-do list.” pl.read_csv() reads the UTF-8 file. The comprehension uses isspace() to find the spaces in each answer and ord() to list their code points in order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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",
)
selected_ids = ["R_GVb9r7EyNijP", "R_oA7M9tOjykZC", "R_asHQHy90yidr"]
selected = survey.filter(pl.col("ResponseId").is_in(selected_ids))
selected["ResponseId"].to_list()
selected["Q_OPEN"].to_list()
[
    [ord(character) for character in text if character.isspace()]
    for text in selected["Q_OPEN"]
]
1
2
3
['R_GVb9r7EyNijP', 'R_oA7M9tOjykZC', 'R_asHQHy90yidr']
['Made a to-do list.', 'Made\xa0a to-do list.', 'Watched\u3000a movie.']
[[32, 32, 32], [160, 32, 32], [12288, 32]]

The ordinary spaces have code point 32. The second answer includes 160, U+00A0, and the third includes 12288, U+3000. Python’s list display shows them as \xa0 and \u3000.

For this comparison of open answers, we treat the two special spaces as word separators equivalent to an ordinary space. This requires a replacement rule in addition to normalization.

In Polars, str.normalize("NFC") creates open_nfc. A second with_columns() call takes that column and replaces U+00A0 and U+3000 with ordinary spaces in open_repaired. With literal=True, str.replace_all() treats each target as literal text. The bracketed pattern in str.contains() tests for either space. Summing the results counts answers containing at least one such space and skips nulls.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
open_answers = survey.select("ResponseId", "Q_OPEN").with_columns(
    open_nfc=pl.col("Q_OPEN").str.normalize("NFC")
)
open_answers = open_answers.with_columns(
    open_repaired=pl.col("open_nfc")
    .str.replace_all("\u00a0", " ", literal=True)
    .str.replace_all("\u3000", " ", literal=True)
)
(
    (open_answers["open_nfc"] != open_answers["Q_OPEN"]).sum(),
    open_answers["open_nfc"].str.contains("[\u00a0\u3000]").sum(),
    open_answers["open_repaired"].str.contains("[\u00a0\u3000]").sum(),
    (open_answers["open_repaired"] != open_answers["Q_OPEN"]).sum(),
)
repaired_selected = open_answers.filter(pl.col("ResponseId").is_in(selected_ids))
repaired_selected["open_repaired"].to_list()
repaired_selected["open_repaired"][0] == repaired_selected["open_repaired"][1]
1
2
3
(4, 6, 0, 10)
['Made a to-do list.', 'Made a to-do list.', 'Watched a movie.']
True

NFC changed four answers. Six others contained one of the two special spaces after normalization and none did after replacement. Ten answers in open_repaired now differ from Q_OPEN. The first two selected answers compare equal once both use ordinary spaces.

Neither special space is canonically equivalent to an ordinary space, so NFC does not replace either with an ordinary space. NFC treats female and Female as different strings. Whether to count them together depends on what those labels mean in the survey.

9.2 Normalizing labels with an explicit mapping

Table 9.1 lists 218 responses written exactly as Female. Which other spellings should count toward that category total? The survey’s Gender categories are Male, Female and Other. F and M stand for Female and Male, and capitalization and spaces at either end do not change the category. A blank means no answer.

Table 9.1. Recorded Gender labels in the survey.

Recorded labelResponsesExact category name
Male229Yes
Female218Yes
Other13Yes
M9No
Male (trailing space)7No
female7No
male7No
` Female` (leading space)6No
F4No
blank3Missing

In gender_working, str_trim() removes whitespace from either end and str_to_lower() converts the label to lowercase. Here the whitespace consists of ordinary spaces. The distinct labels show which spellings still differ. R’s sort() omits missing values by default.

1
2
3
4
gender_labels <- survey |>
  select(ResponseId, Gender) |>
  mutate(gender_working = str_to_lower(str_trim(Gender)))
sort(unique(gender_labels$gender_working))
1
[1] "f"      "female" "m"      "male"   "other" 

The labels Female, ` Female and female now all read female. The abbreviation f` still needs a dictionary entry to associate it with the same category.

dplyr::recode_values() looks up each gender_working label in the dictionary’s working column and returns the corresponding category, or NA if the label is absent. In add_gender(), case_when() tests the recorded Gender first. A blank receives the status missing. A nonblank answer with no dictionary entry receives unmatched. All other answers are mapped. count() gives the number of responses with each status.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
gender_dictionary <- tibble(
  working = c("f", "female", "m", "male", "other"),
  category = c("Female", "Female", "Male", "Male", "Other")
)
add_gender <- function(responses, dictionary) {
  responses |>
    mutate(
      gender = recode_values(
        gender_working,
        from = dictionary$working,
        to = dictionary$category
      )
    ) |>
    mutate(
      gender_status = case_when(
        is.na(Gender) ~ "missing",
        is.na(gender) ~ "unmatched",
        .default = "mapped"
      )
    )
}
gender_mapped <- add_gender(gender_labels, gender_dictionary)
count(gender_mapped, gender_status)
1
2
3
4
5
# A tibble: 2 × 2
  gender_status     n
  <chr>         <int>
1 mapped          500
2 missing           3

The survey has 500 mapped responses and three missing answers.

The survey contains no unmatched label. Four constructed responses show how the same dictionary treats ` Female, F, a missing answer and Nonbinary`. The last label falls outside this survey’s documented categories.

1
2
3
4
5
6
7
gender_examples <- tibble(
  ResponseId = c("x1", "x2", "x3", "x4"),
  Gender = c(" Female", "F", NA, "Nonbinary")
)
gender_examples |>
  mutate(gender_working = str_to_lower(str_trim(Gender))) |>
  add_gender(gender_dictionary)
1
2
3
4
5
6
7
# A tibble: 4 × 5
  ResponseId Gender      gender_working gender gender_status
  <chr>      <chr>       <chr>          <chr>  <chr>        
1 x1         " Female"   female         Female mapped       
2 x2         "F"         f              Female mapped       
3 x3          <NA>       <NA>           <NA>   missing      
4 x4         "Nonbinary" nonbinary      <NA>   unmatched    

Both recognized spellings map to Female. The category is NA for both x3 and x4. In the recorded Gender column, x3 has no answer and x4 says Nonbinary, a label absent from the dictionary.

Counts by category and recorded label show which spellings contribute to each category total. The response IDs should still match the source in number and order.

1
2
3
4
count(gender_mapped, gender, Gender)
count(gender_mapped, gender)
c(nrow(gender_mapped), n_distinct(gender_mapped$ResponseId))
identical(gender_mapped$ResponseId, survey$ResponseId)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# A tibble: 10 × 3
   gender Gender        n
   <chr>  <chr>     <int>
 1 Female " Female"     6
 2 Female "F"           4
 3 Female "Female"    218
 4 Female "female"      7
 5 Male   "M"           9
 6 Male   "Male"      229
 7 Male   "Male "       7
 8 Male   "male"        7
 9 Other  "Other"      13
10 <NA>    <NA>         3
# A tibble: 4 × 2
  gender     n
  <chr>  <int>
1 Female   235
2 Male     252
3 Other     13
4 <NA>       3
[1] 503 503
[1] TRUE

Counting only the exact label Female would miss 17 responses. Seven were recorded as female, six had a space before Female and four used F. Including them gives 235. The other totals are 252 for Male, 13 for Other and three blanks. All 503 response IDs appear in their original order.

In Polars, str.strip_chars(" ") removes only ordinary spaces from the ends, and str.to_lowercase() normalizes case. The distinct values in gender_working show which labels still differ after both operations. The original spelling is recorded separately in Gender.

1
2
3
4
gender_labels = survey.select("ResponseId", "Gender").with_columns(
    gender_working=pl.col("Gender").str.strip_chars(" ").str.to_lowercase()
)
gender_labels["gender_working"].unique().sort().to_list()
1
[None, 'f', 'female', 'm', 'male', 'other']

Trimming spaces and changing case still gives separate entries for f and female, and for m and male. The survey dictionary specifies which category each abbreviation names. The list also includes None for a blank answer.

A blank and an unlisted label can both produce a null category. add_gender() distinguishes them as missing and unmatched. replace_strict() looks up each label from gender_working in the dictionary, with default=None for an unlisted label. Recognized labels are mapped. In .then(), pl.lit() identifies a status such as "missing" as a string literal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
gender_dictionary = {
    "f": "Female",
    "female": "Female",
    "m": "Male",
    "male": "Male",
    "other": "Other",
}


def add_gender(responses, dictionary):
    return responses.with_columns(
        gender=pl.col("gender_working").replace_strict(dictionary, default=None)
    ).with_columns(
        gender_status=pl.when(pl.col("Gender").is_null())
        .then(pl.lit("missing"))
        .when(pl.col("gender").is_null())
        .then(pl.lit("unmatched"))
        .otherwise(pl.lit("mapped"))
    )


gender_mapped = add_gender(gender_labels, gender_dictionary)
gender_mapped.group_by("gender_status").agg(n=pl.len()).sort("gender_status")
1
2
3
4
5
6
7
8
9
shape: (2, 2)
┌───────────────┬─────┐
│ gender_status ┆ n   │
│ ---           ┆ --- │
│ str           ┆ u32 │
╞═══════════════╪═════╡
│ mapped        ┆ 500 │
│ missing       ┆ 3   │
└───────────────┴─────┘

The dictionary maps 500 responses to categories. The other three responses have blank answers.

Four constructed answers show how the same dictionary handles an unlisted label, Nonbinary, alongside ` Female, F` and a null answer.

1
2
3
4
5
6
7
8
9
10
11
12
gender_examples = pl.DataFrame(
    {
        "ResponseId": ["x1", "x2", "x3", "x4"],
        "Gender": [" Female", "F", None, "Nonbinary"],
    }
)
add_gender(
    gender_examples.with_columns(
        gender_working=pl.col("Gender").str.strip_chars(" ").str.to_lowercase()
    ),
    gender_dictionary,
)
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 5)
┌────────────┬───────────┬────────────────┬────────┬───────────────┐
│ ResponseId ┆ Gender    ┆ gender_working ┆ gender ┆ gender_status │
│ ---        ┆ ---       ┆ ---            ┆ ---    ┆ ---           │
│ str        ┆ str       ┆ str            ┆ str    ┆ str           │
╞════════════╪═══════════╪════════════════╪════════╪═══════════════╡
│ x1         ┆  Female   ┆ female         ┆ Female ┆ mapped        │
│ x2         ┆ F         ┆ f              ┆ Female ┆ mapped        │
│ x3         ┆ null      ┆ null           ┆ null   ┆ missing       │
│ x4         ┆ Nonbinary ┆ nonbinary      ┆ null   ┆ unmatched     │
└────────────┴───────────┴────────────────┴────────┴───────────────┘

The first two rows map to Female. The null answer is missing, whereas Nonbinary is unmatched. Their category cells are both null, so the status and recorded Gender show why each category is missing.

Counts by category and recorded Gender label show which spellings contribute to each category total. The response IDs should still match survey in number and order.

1
2
3
4
5
6
7
8
(
    gender_mapped.group_by("gender", "Gender")
    .agg(n=pl.len())
    .sort("gender", "Gender", nulls_last=True)
)
gender_mapped.group_by("gender").agg(n=pl.len()).sort("gender", nulls_last=True)
(gender_mapped.height, gender_mapped["ResponseId"].n_unique())
gender_mapped["ResponseId"].equals(survey["ResponseId"])
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
shape: (10, 3)
┌────────┬─────────┬─────┐
│ gender ┆ Gender  ┆ n   │
│ ---    ┆ ---     ┆ --- │
│ str    ┆ str     ┆ u32 │
╞════════╪═════════╪═════╡
│ Female ┆  Female ┆ 6   │
│ Female ┆ F       ┆ 4   │
│ Female ┆ Female  ┆ 218 │
│ Female ┆ female  ┆ 7   │
│ Male   ┆ M       ┆ 9   │
│ Male   ┆ Male    ┆ 229 │
│ Male   ┆ Male    ┆ 7   │
│ Male   ┆ male    ┆ 7   │
│ Other  ┆ Other   ┆ 13  │
│ null   ┆ null    ┆ 3   │
└────────┴─────────┴─────┘
shape: (4, 2)
┌────────┬─────┐
│ gender ┆ n   │
│ ---    ┆ --- │
│ str    ┆ u32 │
╞════════╪═════╡
│ Female ┆ 235 │
│ Male   ┆ 252 │
│ Other  ┆ 13  │
│ null   ┆ 3   │
└────────┴─────┘
(503, 503)
True

The 218 exact Female labels, seven female labels, six with a leading space and four F labels give 235 responses in the category. The table also counts Male and Male separately. They look alike in the display, but the 229 exact labels and the seven with a trailing space occupy different rows. All 503 response IDs appear in their original order.

Replacing a spelling variant

The agreement items use Strongly disagree, Disagree, Neutral, Agree and Strongly agree. In SAT_5, the spelling Strongly Agree also means Strongly agree. A dictionary lookup that returns a missing value for unlisted labels would also turn the refusal code -99 into a missing value. Replacing only the specified spelling leaves the refusal codes and other labels unchanged.

dplyr::replace_values() takes an old ~ new pair and changes only that spelling in sat_5_label. The recorded SAT_5 shows which response originally used a capital A.

1
2
3
4
5
sat_5 <- survey |>
  select(ResponseId, SAT_5) |>
  mutate(sat_5_label = replace_values(SAT_5, "Strongly Agree" ~ "Strongly agree"))
filter(sat_5, SAT_5 == "Strongly Agree")
count(sat_5, sat_5_label, SAT_5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# A tibble: 1 × 3
  ResponseId     SAT_5          sat_5_label   
  <chr>          <chr>          <chr>         
1 R_95DSbCu9tEU4 Strongly Agree Strongly agree
# A tibble: 8 × 3
  sat_5_label       SAT_5                 n
  <chr>             <chr>             <int>
1 -99               -99                   2
2 Agree             Agree                70
3 Disagree          Disagree             89
4 Neutral           Neutral             115
5 Strongly agree    Strongly Agree        1
6 Strongly agree    Strongly agree      111
7 Strongly disagree Strongly disagree   107
8 <NA>              <NA>                  8

For response R_95DSbCu9tEU4, SAT_5 reads Strongly Agree. Its new label matches the 111 responses already recorded as Strongly agree. The two refusals still read -99, and the eight blank answers are still missing.

Polars replace() with {"Strongly Agree": "Strongly agree"} changes only that spelling. Unlike replace_strict(), it returns values not found among the keys unchanged. The counts by SAT_5 and sat_5_label show how many responses had each spelling.

1
2
3
4
5
6
7
8
9
sat_5 = survey.select("ResponseId", "SAT_5").with_columns(
    sat_5_label=pl.col("SAT_5").replace({"Strongly Agree": "Strongly agree"})
)
sat_5.filter(pl.col("SAT_5") == "Strongly Agree")
(
    sat_5.group_by("sat_5_label", "SAT_5")
    .agg(n=pl.len())
    .sort("sat_5_label", "SAT_5", 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
shape: (1, 3)
┌────────────────┬────────────────┬────────────────┐
│ ResponseId     ┆ SAT_5          ┆ sat_5_label    │
│ ---            ┆ ---            ┆ ---            │
│ str            ┆ str            ┆ str            │
╞════════════════╪════════════════╪════════════════╡
│ R_95DSbCu9tEU4 ┆ Strongly Agree ┆ Strongly agree │
└────────────────┴────────────────┴────────────────┘
shape: (8, 3)
┌───────────────────┬───────────────────┬─────┐
│ sat_5_label       ┆ SAT_5             ┆ n   │
│ ---               ┆ ---               ┆ --- │
│ str               ┆ str               ┆ u32 │
╞═══════════════════╪═══════════════════╪═════╡
│ -99               ┆ -99               ┆ 2   │
│ Agree             ┆ Agree             ┆ 70  │
│ Disagree          ┆ Disagree          ┆ 89  │
│ Neutral           ┆ Neutral           ┆ 115 │
│ Strongly agree    ┆ Strongly Agree    ┆ 1   │
│ Strongly agree    ┆ Strongly agree    ┆ 111 │
│ Strongly disagree ┆ Strongly disagree ┆ 107 │
│ null              ┆ null              ┆ 8   │
└───────────────────┴───────────────────┴─────┘

Response R_95DSbCu9tEU4 has Strongly Agree in SAT_5 and Strongly agree in sat_5_label. The new column also contains the two -99 refusal codes and the eight nulls.

9.3 Detecting, extracting, and splitting patterns

Which Stroop filenames identify a participant’s run? sub-007_ses-1.csv is run 1 for participant 007 in session 1. A second run adds _run-2, as in sub-007_ses-1_run-2.csv. The lookup file stimuli.csv has no run number either. Assigning run 1 makes sense only if the name identifies a participant and session.

A regular expression is a pattern for matching text. This one checks the participant and session part of a filename. In the R string "\\Asub-\\d+_ses-\\d+\\z", each \\ represents one backslash in the pattern. \A and \z require the very start and end of the string. \d matches a digit, and + requires one or more digits.

An extra initial x, a missing participant number or a final newline prevents a match. In stringr, $ can match just before a final newline, so the pattern with ^ and $ accepts the fourth example.

1
2
3
4
5
6
7
8
9
file_names <- c(
  "sub-007_ses-1.csv",
  "sub-007_ses-1_run-2.csv",
  "stimuli.csv",
  "sub-007_ses-1.csv\n"
)
core_examples <- c("sub-007_ses-1", "xsub-007_ses-1", "sub-_ses-1", "sub-007_ses-1\n")
str_detect(core_examples, "\\Asub-\\d+_ses-\\d+\\z")
str_detect(core_examples, "^sub-\\d+_ses-\\d+$")
1
2
[1]  TRUE FALSE FALSE FALSE
[1]  TRUE FALSE FALSE  TRUE

The full pattern adds an optional run and the .csv ending. The parentheses around each \d+ capture the matching digits for participant, session and run. In (?:_run-(\d+))?, the outer parentheses group the run suffix without capturing it, and the final ? makes the whole suffix optional. \. requires a literal dot. By default, a bare . matches any character except a line break, so it accepts the x in sub-007_ses-1xcsv.

1
2
3
4
file_pattern <- "\\Asub-(\\d+)_ses-(\\d+)(?:_run-(\\d+))?\\.csv\\z"
dot_examples <- c("sub-007_ses-1.csv", "sub-007_ses-1_run-2.csv", "sub-007_ses-1xcsv")
str_detect(dot_examples, file_pattern)
str_detect("sub-007_ses-1xcsv", "\\Asub-(\\d+)_ses-(\\d+)(?:_run-(\\d+))?.csv\\z")
1
2
[1]  TRUE  TRUE FALSE
[1] TRUE

str_detect() gives each of the four filenames a TRUE or FALSE in the matches column.

1
2
files <- tibble(file_name = file_names, matches = str_detect(file_names, file_pattern))
files
1
2
3
4
5
6
7
# A tibble: 4 × 2
  file_name                 matches
  <chr>                     <lgl>  
1 "sub-007_ses-1.csv"       TRUE   
2 "sub-007_ses-1_run-2.csv" TRUE   
3 "stimuli.csv"             FALSE  
4 "sub-007_ses-1.csv\n"     FALSE  

Only the two participant files match. In the fourth name, a newline follows .csv, so the pattern does not reach the end of the string. The name stimuli.csv has no participant or session number.

str_match() returns a character matrix with one row per filename. The first column is the whole match. The next three contain the participant, session and run digits. In parts[, 2], the empty row index selects the participant capture for every name.

The run column alone cannot distinguish a matching name with no suffix from stimuli.csv. Both have NA there. case_when() checks matches before assigning run 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
parts <- str_match(file_names, file_pattern)
parts
files <- files |>
  mutate(
    participant = parts[, 2],
    session = parts[, 3],
    run_recorded = parts[, 4]
  ) |>
  mutate(
    run = case_when(
      !matches ~ NA,
      is.na(run_recorded) ~ "1",
      .default = run_recorded
    )
  )
select(files, file_name, participant, session, run_recorded, run)
1
2
3
4
5
6
7
8
9
10
11
12
     [,1]                      [,2]  [,3] [,4]
[1,] "sub-007_ses-1.csv"       "007" "1"  NA  
[2,] "sub-007_ses-1_run-2.csv" "007" "1"  "2" 
[3,] NA                        NA    NA   NA  
[4,] NA                        NA    NA   NA  
# A tibble: 4 × 5
  file_name                 participant session run_recorded run  
  <chr>                     <chr>       <chr>   <chr>        <chr>
1 "sub-007_ses-1.csv"       007         1       <NA>         1    
2 "sub-007_ses-1_run-2.csv" 007         1       2            2    
3 "stimuli.csv"             <NA>        <NA>    <NA>         <NA> 
4 "sub-007_ses-1.csv\n"     <NA>        <NA>    <NA>         <NA> 

Both matching files give participant 007 and session 1. The unsuffixed file receives run 1 and the other has its recorded run 2. The two nonmatching names have NA in both run columns.

Python’s re module handles regular expressions. The first pattern checks the participant and session part of the filename. In the raw string r"sub-\d+_ses-\d+", the backslashes are included in the pattern. \d matches a digit and + requires one or more. re.fullmatch() returns a match object only if the whole string matches. Otherwise it returns None.

Of the four examples, only sub-007_ses-1 matches in full. With re.match() and $, the last example also passes because $ can match just before the final newline.

1
2
3
4
5
6
7
8
9
10
11
import re

file_names = [
    "sub-007_ses-1.csv",
    "sub-007_ses-1_run-2.csv",
    "stimuli.csv",
    "sub-007_ses-1.csv\n",
]
core_examples = ["sub-007_ses-1", "xsub-007_ses-1", "sub-_ses-1", "sub-007_ses-1\n"]
[re.fullmatch(r"sub-\d+_ses-\d+", text) is not None for text in core_examples]
[re.match(r"sub-\d+_ses-\d+$", text) is not None for text in core_examples]
1
2
[True, False, False, False]
[True, False, False, True]

Parentheses group part of a pattern and also capture the text it matches, so that text can be extracted separately. The group (?:_run-(\d+))? accepts an optional run. Here ? makes the outer group optional, and ?: prevents that outer group from being captured. The three capturing groups extract the participant, session and run digits. The suffix starts with a literal dot, written \.. A bare dot would also match the x in sub-007_ses-1xcsv, since it matches any character except a line break by default.

1
2
3
4
5
file_pattern = r"sub-(\d+)_ses-(\d+)(?:_run-(\d+))?\.csv"
re.fullmatch(file_pattern, "sub-007_ses-1_run-2.csv")
dot_examples = ["sub-007_ses-1.csv", "sub-007_ses-1_run-2.csv", "sub-007_ses-1xcsv"]
[re.fullmatch(file_pattern, text) is not None for text in dot_examples]
re.fullmatch(r"sub-(\d+)_ses-(\d+)(?:_run-(\d+))?.csv", "sub-007_ses-1xcsv") is not None
1
2
3
<re.Match object; span=(0, 23), match='sub-007_ses-1_run-2.csv'>
[True, True, False]
True

For each filename, re.fullmatch() returns a match object or None. Testing each result with is not None gives one Boolean per name.

1
2
matches = [re.fullmatch(file_pattern, name) for name in file_names]
[match is not None for match in matches]
1
[True, True, False, False]

The two participant files match. Neither stimuli.csv nor the name with a trailing newline does.

For a matching filename, match.groups() returns the participant and session digits and, if present, the run digits. When a matching name has no run number, its third value is None and the code assigns run "1". A name that fails the pattern never reaches that step. Each tuple in parsed pairs a matching filename with its fields.

1
2
3
4
5
6
7
8
9
10
parsed = []
for name in file_names:
    match = re.fullmatch(file_pattern, name)
    if match is not None:
        participant, session, run = match.groups()
        if run is None:
            run = "1"
        parsed.append((name, participant, session, run))

parsed
1
[('sub-007_ses-1.csv', '007', '1', '1'), ('sub-007_ses-1_run-2.csv', '007', '1', '2')]

The parsed list contains only the two participant filenames, with runs '1' and '2'. The participant identifier is the string '007', including its leading zeros.

Splitting at a known delimiter

The filename pattern both validates a structure and extracts fields with different meanings. A list of selected survey options poses a simpler separation problem: each semicolon marks the boundary between choices of the same kind. Q_MULTI records the numbers of the stress-reduction options a respondent chose.

To make each choice available separately, stringr::str_split() splits the 1;3;5 recorded for response R_nMxPhW4zivOi at each semicolon. The result is a list column named options, with one character vector per response. multi_split$options[[1]] retrieves all the choices for the first response.

1
2
3
4
5
6
7
multi <- survey |>
  filter(ResponseId == "R_nMxPhW4zivOi") |>
  select(ResponseId, Q_MULTI)
multi_split <- mutate(multi, options = str_split(Q_MULTI, ";"))
select(multi_split, ResponseId, Q_MULTI)
multi_split$options[[1]]
nrow(multi_split)
1
2
3
4
5
6
# A tibble: 1 × 2
  ResponseId     Q_MULTI
  <chr>          <chr>  
1 R_nMxPhW4zivOi 1;3;5  
[1] "1" "3" "5"
[1] 1

The entry contains "1", "3" and "5", but the tibble still has one response row.

Python’s string split() returns a list of pieces. Polars str.split(";") creates a list column called options, so several choices can belong to one response. Here [0] and to_list() show the choices inside the first cell. The DataFrame’s height counts responses.

1
2
3
4
5
6
"1;3;5".split(";")
multi = survey.filter(pl.col("ResponseId") == "R_nMxPhW4zivOi").select("ResponseId", "Q_MULTI")
multi_split = multi.with_columns(options=pl.col("Q_MULTI").str.split(";"))
multi_split.select("ResponseId", "Q_MULTI").rows()
multi_split["options"][0].to_list()
multi_split.height
1
2
3
4
['1', '3', '5']
[('R_nMxPhW4zivOi', '1;3;5')]
['1', '3', '5']
1

The list contains three option strings. The height of 1 counts the single questionnaire on which those options were selected.

9.4 Category labels, levels, and order

Once recorded answers use the intended category labels, reporting them also requires an order. The agreement scale runs from Strongly disagree through Disagree, Neutral and Agree to Strongly agree. Only three labels occur in the six constructed responses below, and one answer is blank. Alphabetical sorting puts Agree before Strongly disagree. The observed labels alone cannot tell us where the unused options Disagree and Neutral belong. To report all five options in questionnaire order, we need the scale’s own list.

A factor is R’s type for categorical data. Its possible labels are called levels. In factor(), the levels argument lists all five labels in questionnaire order, including the two absent here. With ordered = TRUE, comparisons follow that order. The final call tests Strongly Agree, a spelling outside the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
agreement_levels <- c(
  "Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"
)
answers <- tibble(
  response_id = c("a1", "a2", "a3", "a4", "a5", "a6"),
  answer = c(
    "Agree", "Strongly agree", "Strongly disagree", "Agree", NA, "Strongly agree"
  )
)
sort(unique(answers$answer))
answers <- mutate(
  answers,
  answer_level = factor(answer, levels = agreement_levels, ordered = TRUE)
)
levels(answers$answer_level)
answers$answer_level
factor("Strongly Agree", levels = agreement_levels, ordered = TRUE)
1
2
3
4
5
6
7
8
[1] "Agree"             "Strongly agree"    "Strongly disagree"
[1] "Strongly disagree" "Disagree"          "Neutral"          
[4] "Agree"             "Strongly agree"   
[1] Agree             Strongly agree    Strongly disagree Agree            
[5] <NA>              Strongly agree   
5 Levels: Strongly disagree < Disagree < Neutral < ... < Strongly agree
[1] <NA>
5 Levels: Strongly disagree < Disagree < Neutral < ... < Strongly agree

All five levels are declared even though only three occur. The printed < marks their order. The blank answer for a5 appears as <NA>. The separate call with "Strongly Agree" also returns <NA> because the spelling is outside the list. From the factor alone, both look like unanswered items.

A factor stores each value as the position of its label in the level list. Without an explicit levels argument, factor() sorts the observed labels. Here that puts Agree first.

1
2
as.integer(answers$answer_level)
as.integer(factor(answers$answer))
1
2
[1]  4  5  1  4 NA  5
[1]  1  2  3  1 NA  2

Agree receives code 4 under the declared order but code 1 under the alphabetical order. These integers locate labels in a list. They do not by themselves assign measurement scores.

Here the default dplyr::count() lists the answer levels present in the subset and the missing answer. For this factor, .drop = FALSE also includes declared levels with no responses.

1
2
count(answers, answer_level)
count(answers, answer_level, .drop = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# A tibble: 4 × 2
  answer_level          n
  <ord>             <int>
1 Strongly disagree     1
2 Agree                 2
3 Strongly agree        2
4 <NA>                  1
# A tibble: 6 × 2
  answer_level          n
  <ord>             <int>
1 Strongly disagree     1
2 Disagree              0
3 Neutral               0
4 Agree                 2
5 Strongly agree        2
6 <NA>                  1

Disagree and Neutral each have a count of zero because nobody chose them. The separate NA row counts the one unanswered item.

A Polars Enum declares a fixed list of categories in order. cast() converts the answer column to that type, so sorting follows the scale. to_physical() gives each value’s position in the list, counting from zero. The separate cast tests the unlisted spelling Strongly Agree.

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
agreement_levels = [
    "Strongly disagree",
    "Disagree",
    "Neutral",
    "Agree",
    "Strongly agree",
]
agreement = pl.Enum(agreement_levels)
answers = pl.DataFrame(
    {
        "response_id": ["a1", "a2", "a3", "a4", "a5", "a6"],
        "answer": [
            "Agree",
            "Strongly agree",
            "Strongly disagree",
            "Agree",
            None,
            "Strongly agree",
        ],
    }
)
answers["answer"].unique().sort().to_list()
answers = answers.with_columns(answer_level=pl.col("answer").cast(agreement))
agreement.categories.to_list()
answers["answer_level"].sort().to_list()
answers["answer_level"].to_physical().to_list()
1
2
3
4
[None, 'Agree', 'Strongly agree', 'Strongly disagree']
['Strongly disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly agree']
[None, 'Strongly disagree', 'Agree', 'Agree', 'Strongly agree', 'Strongly agree']
[3, 4, 0, 3, None, 4]
1
2
# Deliberate error: a label outside the declared categories
pl.Series("answer", ["Strongly Agree"]).cast(agreement)
1
polars.exceptions.InvalidOperationError: conversion from `str` to `enum` failed in column 'answer' for 1 out of 1 values: ["Strongly Agree"]

The sorted Enum follows the questionnaire order. to_physical() reads the original row order, so its first code, 3, belongs to Agree, the fourth label. That position does not assign an item score. The error identifies Strongly Agree, with a capital A, as the label the default cast rejects.

Categorical instead builds its category mapping from encountered values without a declared list. It sorts by label, and its physical codes can depend on category mappings already present in the session.

1
2
3
categorical_answer = answers["answer"].cast(pl.Categorical)
categorical_answer.sort().to_list()
categorical_answer.to_physical().to_list()
1
2
[None, 'Agree', 'Agree', 'Strongly agree', 'Strongly agree', 'Strongly disagree']
[0, 1, 2, 0, None, 1]

The Categorical column puts Strongly agree before Strongly disagree because it sorts by label text. Only the three observed labels appear in this output. Neither their order nor their physical codes tell us where the unobserved Disagree and Neutral belong on the scale.

Grouping by answer_level counts the values present in these six responses, including the null for a5. Counting matches for each label in agreement_levels gives the new DataFrame one row per scale category, even when the count is zero. null_count() counts unanswered items separately.

1
2
3
4
5
6
7
8
answers.group_by("answer_level").agg(n=pl.len()).sort("answer_level")
pl.DataFrame(
    {
        "answer_level": agreement_levels,
        "n": [(answers["answer_level"] == level).sum() for level in agreement_levels],
    }
)
answers["answer_level"].null_count()
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)
┌───────────────────┬─────┐
│ answer_level      ┆ n   │
│ ---               ┆ --- │
│ enum              ┆ u32 │
╞═══════════════════╪═════╡
│ null              ┆ 1   │
│ Strongly disagree ┆ 1   │
│ Agree             ┆ 2   │
│ Strongly agree    ┆ 2   │
└───────────────────┴─────┘
shape: (5, 2)
┌───────────────────┬─────┐
│ answer_level      ┆ n   │
│ ---               ┆ --- │
│ str               ┆ i64 │
╞═══════════════════╪═════╡
│ Strongly disagree ┆ 1   │
│ Disagree          ┆ 0   │
│ Neutral           ┆ 0   │
│ Agree             ┆ 2   │
│ Strongly agree    ┆ 2   │
└───────────────────┴─────┘
1

The complete table lists all five scale categories. Disagree and Neutral each have zero responses. The separate null count of 1 refers to the unanswered item.

The separate Strongly Agree test concerns a recorded answer, whereas a5 has no answer. The survey treats Strongly Agree as another spelling of Strongly agree, so mapping that spelling before conversion assigns the intended category. Converting it to a missing value would lose an answer that belongs in the category count.

Category order and numerical meaning

Some category lists have no substantive order. The survey’s Region field records one of 17 region names with no ranking, which makes region a nominal variable. Codes such as 01 through 17 would only identify the regions, and differences between those numbers would measure no geographic quantity. Agreement categories do have an order, but that order alone does not specify equal distances or numerical scores.

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