Post

Reusing Calculations Across Columns and Files

If code for counting answers is copied across ten survey items, a change in the rule requires ten edits. We need a way to define the rule once while specifying which input it should process. This chapter applies functions to repeated work on tables, beginning with a summary whose minimum response requirement can be changed through an argument. We then supply column names or calculations, apply a rule across selected columns, and extend the approach to a collection of files. Recording the item or file behind each result lets us check what was processed and what contributed to the combined output.

15.1 Turning a repeated transformation into a function

A rule about when a mean can be reported should be applied consistently to every response. In a constructed example, one respondent has scores of 2 and 4 on two items and no score on a third. If we require two answers, we can report a mean. What can we still report if we require three? The minimum is an argument to the function, so we can compare both rules on the same scores.

The function returns three values. The count and sum use all observed scores. The mean is missing unless the count is positive and meets the minimum. Requiring a positive count avoids division by zero even when the minimum is 0. When the mean is missing, a count of zero means no scores were observed. A positive count means some were observed but too few to report a mean.

In R, observed_summary() requires both values and min_observed. sum(!is.na(values)) counts the observed values, and sum() with na.rm = TRUE adds them. is.na() is also TRUE for NaN, so the count and sum exclude it.

The if condition uses && to test whether the count is positive and reaches the minimum. If the count is zero, && skips the second test and the mean is NA_real_. The function returns a named vector. at_two and at_three store the results for minimum counts of 2 and 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
library(tidyverse)

values <- c(2, 4, NA)
observed_summary <- function(values, min_observed) {
  n_observed <- sum(!is.na(values))
  total <- sum(values, na.rm = TRUE)
  if (n_observed > 0 && n_observed >= min_observed) {
    mean <- total / n_observed
  } else {
    mean <- NA_real_
  }
  c(n_observed = n_observed, sum = total, mean = mean)
}
at_two <- observed_summary(values, min_observed = 2)
at_three <- observed_summary(values, min_observed = 3)
at_two
at_three
1
2
3
4
n_observed        sum       mean 
         2          6          3 
n_observed        sum       mean 
         2          6         NA 

To identify what changes when the minimum rises from 2 to 3, the == comparison pairs the two counts, the two sums, and the two means by their positions in the vectors.

1
at_two == at_three
1
2
n_observed        sum       mean 
      TRUE       TRUE         NA 

The counts and sums compare equal: both calls describe two observed scores with a sum of 6. Comparing the means gives NA, an unknown answer, because one mean is unavailable. With a minimum of 2, the function reports the mean 6/2 = 3; with a minimum of 3, it reports NA. Changing the requirement changes whether a mean is reported, without changing the observed values that the count and sum describe.

In Python, observed_summary() takes a Polars Series of type Float64 and a required minimum. drop_nulls() removes nulls and drop_nans() removes NaN values. len() counts the observed scores, and sum() adds them. If the count is zero, Python’s and skips the minimum-count test. The function returns a dictionary with keys n_observed, sum, and mean, using None when the mean is unavailable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import polars as pl

values = pl.Series("value", [2.0, 4.0, None], dtype=pl.Float64)


def observed_summary(values, min_observed):
    observed = values.drop_nulls().drop_nans()
    n_observed = observed.len()
    total = observed.sum()
    if n_observed > 0 and n_observed >= min_observed:
        mean = total / n_observed
    else:
        mean = None
    return {"n_observed": n_observed, "sum": total, "mean": mean}


at_two = observed_summary(values, min_observed=2)
at_three = observed_summary(values, min_observed=3)
at_two
at_three
1
2
{'n_observed': 2, 'sum': 6.0, 'mean': 3.0}
{'n_observed': 2, 'sum': 6.0, 'mean': None}

The dictionaries report the sum as a float because the Series contains floats. To identify what changes with the higher minimum, the comprehension compares each count, sum, and mean in at_two with its counterpart in at_three.

1
[at_two[key] == at_three[key] for key in at_two]
1
[True, True, False]

The two True results confirm the same count of 2 and sum of 6.0. The last comparison is False because Python evaluates 3.0 == None as false. The minimum of 2 permits the mean 3.0; the minimum of 3 makes it unavailable. Both calls still report the observed count and sum, so an unavailable mean does not erase the information needed to explain it.

15.2 Supplying a column name or a calculation

The summary function received the values themselves. For a calculation on a table, we may instead want to specify which column it should use. If we give a function the name "SAT_1", how can it count the entries in that survey column? With the same 503 forms, changing the argument to "SAT_7" should give the count for that item. Only blanks are excluded here; a refusal or an invalid code still counts as recorded text.

Here readr::read_csv() reads all survey columns as text and treats a blank answer as NA with na = "". count_observed() receives a table and column, the name as text. Inside summarise(), .data[[column]] retrieves the data column named by that text, while .env$column places the text itself in the output.

The second function, count_bare(), uses the argument directly instead of looking up the data column. Both calls receive the string "SAT_1", so their results reveal the difference between counting a name and counting the values it identifies.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
survey <- read_csv(
  "data/practice/survey.csv",
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
count_observed <- function(data, column) {
  summarise(
    data,
    column = .env$column,
    n_rows = n(),
    n_observed = sum(!is.na(.data[[column]]))
  )
}
sat_1_summary <- count_observed(survey, "SAT_1")
sat_1_summary

count_bare <- function(data, column) {
  summarise(data, n_observed = sum(!is.na(column)))
}
count_bare(survey, "SAT_1")
1
2
3
4
5
6
7
8
# A tibble: 1 × 3
  column n_rows n_observed
  <chr>   <int>      <int>
1 SAT_1     503        493
# A tibble: 1 × 1
  n_observed
       <int>
1          1

Why does count_bare() return 1 when count_observed() finds 493 nonblank answers? Inside dplyr::summarise(), a bare name can refer to a column or to a variable in the function. The survey has no field named column, so !is.na(column) tests the single string "SAT_1". With .data[[column]], the same string selects all 503 entries in SAT_1.

Calling the function with "SAT_7" changes the selected item. bind_rows() stacks its summary under the first one.

1
2
sat_7_summary <- count_observed(survey, "SAT_7")
bind_rows(sat_1_summary, sat_7_summary)
1
2
3
4
5
# A tibble: 2 × 3
  column n_rows n_observed
  <chr>   <int>      <int>
1 SAT_1     503        493
2 SAT_7     503        489

The same 503 responses now give 489 nonblank answers for SAT_7. The output includes the column name, so each count can be matched to its item after stacking.

pl.read_csv() reads the survey columns as text with infer_schema=False. Here blank answers become nulls. pl.col("SAT_1") constructs a column expression from text. count_observed() builds that reference from its column argument and evaluates it in select() on data. is_not_null().sum() counts nonblank answers, and pl.len() counts rows.

The summary must also identify which item was counted. pl.lit(column) adds the name as a literal value. Without pl.lit(), select() would treat the string as a reference to the column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
survey = pl.read_csv("data/practice/survey.csv", infer_schema=False)
print(pl.col("SAT_1"))


def count_observed(data, column):
    return data.select(
        column=pl.lit(column),
        n_rows=pl.len(),
        n_observed=pl.col(column).is_not_null().sum(),
    )


sat_1_summary = count_observed(survey, "SAT_1")
sat_1_summary
1
2
3
4
5
6
7
8
9
col("SAT_1")
shape: (1, 3)
┌────────┬────────┬────────────┐
│ column ┆ n_rows ┆ n_observed │
│ ---    ┆ ---    ┆ ---        │
│ str    ┆ u32    ┆ u32        │
╞════════╪════════╪════════════╡
│ SAT_1  ┆ 503    ┆ 493        │
└────────┴────────┴────────────┘

The printed expression, col("SAT_1"), names the column but contains none of its values. Evaluating it in the summary gives 493 nonblank answers among 503 responses.

The call with "SAT_7" counts a different item in the same survey. pl.concat(..., how="vertical") stacks the two summaries, whose column names and order must match. Comparing their schemas also checks the types.

1
2
3
sat_7_summary = count_observed(survey, "SAT_7")
pl.concat([sat_1_summary, sat_7_summary], how="vertical")
sat_1_summary.schema == sat_7_summary.schema
1
2
3
4
5
6
7
8
9
10
shape: (2, 3)
┌────────┬────────┬────────────┐
│ column ┆ n_rows ┆ n_observed │
│ ---    ┆ ---    ┆ ---        │
│ str    ┆ u32    ┆ u32        │
╞════════╪════════╪════════════╡
│ SAT_1  ┆ 503    ┆ 493        │
│ SAT_7  ┆ 503    ┆ 489        │
└────────┴────────┴────────────┘
True

The second item has 489 nonblank answers. The final True confirms that changing the item did not change the summary’s column names and types.

count_observed() constructs an expression and immediately evaluates it on the supplied table. A function can also return the expression for evaluation later. A familiar seconds-to-minutes conversion makes that distinction visible without the additional steps of counting answers. minutes_from() receives only a column name: what can it return before there are any durations to divide?

1
2
3
4
5
6
7
def minutes_from(column):
    return pl.col(column) / 60


minutes_expr = minutes_from("seconds")
type(minutes_expr)
print(minutes_expr)
1
2
<class 'polars.expr.expr.Expr'>
[(col("seconds")) / (dyn int: 60)]

The result is a Polars expression, or Expr. It specifies which column to divide by 60. The duration values come from the table where the expression is evaluated.

durations contains three constructed response times of 30, 90, and 120 seconds. with_columns() evaluates minutes_expr against this table and adds the result as minutes.

1
2
3
4
durations = pl.DataFrame(
    {"response_id": ["r1", "r2", "r3"], "seconds": [30, 90, 120]}
)
durations.with_columns(minutes=minutes_expr)
1
2
3
4
5
6
7
8
9
10
shape: (3, 3)
┌─────────────┬─────────┬─────────┐
│ response_id ┆ seconds ┆ minutes │
│ ---         ┆ ---     ┆ ---     │
│ str         ┆ i64     ┆ f64     │
╞═════════════╪═════════╪═════════╡
│ r1          ┆ 30      ┆ 0.5     │
│ r2          ┆ 90      ┆ 1.5     │
│ r3          ┆ 120     ┆ 2.0     │
└─────────────┴─────────┴─────────┘

The expression produces 0.5, 1.5, and 2.0 minutes beside the source times. It can also run on another table with a numeric seconds column.

In to_minutes(90), the argument already contains a duration. minutes_from("seconds") describes the same division for a named column.

1
2
3
4
5
6
7
def to_minutes(seconds):
    return seconds / 60


to_minutes(90)
type(to_minutes(90))
(callable(to_minutes), callable(minutes_from))
1
2
3
1.5
<class 'float'>
(True, True)

callable() gives True for both functions. Calling to_minutes(90) returns the float 1.5 immediately. Calling minutes_from("seconds") returns the expression that with_columns() evaluates on the table.

Table 15.1. Names, values, functions, and expressions in the Polars examples.

KindExampleMeaning in this exampleHow it is used
Column name"SAT_1"Text identifying a survey itempl.col("SAT_1") refers to that column in select()
Computed columnminutes0.5, 1.5, and 2.0 minutesAvailable beside seconds in the table returned by with_columns()
Callableto_minutesA function that divides its argument by 60to_minutes(90) returns 1.5
Expressionminutes_exprDivision of the seconds column by 60with_columns(minutes=minutes_expr) evaluates it on durations

15.3 Applying a calculation to several columns

Changing a column-name argument let us count answers for SAT_1 and SAT_7. To compare all ten satisfaction items, we can apply the same calculation to a selected set of columns. How many answers are blank in each item?

The selection must identify the intended items. Every column beginning with S would also include Start Date and the stress items. The dplyr selection starts_with("SAT_") and the Polars expression pl.col("^SAT_.*$") select just the satisfaction items.

1
2
3
4
5
6
7
8
9
survey <- read_csv(
  "data/practice/survey.csv",
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
sat_items <- names(select(survey, starts_with("SAT_")))
sat_items
ncol(select(survey, starts_with("S")))
1
2
3
 [1] "SAT_1"  "SAT_2"  "SAT_3"  "SAT_4"  "SAT_5"  "SAT_6"  "SAT_7"  "SAT_8" 
 [9] "SAT_9"  "SAT_10"
[1] 21
1
2
3
4
survey = pl.read_csv("data/practice/survey.csv", infer_schema=False)
sat_items = survey.select(pl.col("^SAT_.*$")).columns
sat_items
len(survey.select(pl.col("^S.*$")).columns)
1
2
['SAT_1', 'SAT_2', 'SAT_3', 'SAT_4', 'SAT_5', 'SAT_6', 'SAT_7', 'SAT_8', 'SAT_9', 'SAT_10']
21

The selected names are exactly SAT_1 through SAT_10. The broader prefix selects 21 fields because it also includes Start Date and the ten stress items. The ten-name list is stored as sat_items.

Empty fields are NA in R and null in Polars. A refusal or invalid code is recorded text. In the three-value example below, which entries count as blank? In R, count_blank() counts missing values in a vector. In Polars, is_null().sum() counts them in a Series.

1
2
3
4
5
count_blank <- function(x) {
  sum(is.na(x))
}
miniature <- c("Agree", NA, "-99")
count_blank(miniature)
1
[1] 1
1
2
miniature = pl.Series("answer", ["Agree", None, "-99"])
miniature.is_null().sum()
1
1

Both counts are 1. The refusal code -99 is present in the data, even though it cannot be used as an agreement score.

In R, across() repeats a calculation over selected columns inside summarise(). all_of(sat_items) selects the stored names and requires each to exist. The second argument is count_blank, passed without parentheses so that across() can call it for each column. Each returned count has its source column’s name.

1
2
blank_counts <- summarise(survey, across(all_of(sat_items), count_blank))
blank_counts
1
2
3
4
# A tibble: 1 × 10
  SAT_1 SAT_2 SAT_3 SAT_4 SAT_5 SAT_6 SAT_7 SAT_8 SAT_9 SAT_10
  <int> <int> <int> <int> <int> <int> <int> <int> <int>  <int>
1    10    10     9     7     8    11    14    10    13     14

The wide summary places ten counts in one row. pivot_longer() makes one row per item. everything() selects the columns, item receives their names, and n_blank receives the counts. Counting the blanks in survey$SAT_7 gives us a check on the row labeled SAT_7.

1
2
3
4
5
6
7
8
blank_long <- pivot_longer(
  blank_counts,
  everything(),
  names_to = "item",
  values_to = "n_blank"
)
blank_long
sum(is.na(survey$SAT_7))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# A tibble: 10 × 2
   item   n_blank
   <chr>    <int>
 1 SAT_1       10
 2 SAT_2       10
 3 SAT_3        9
 4 SAT_4        7
 5 SAT_5        8
 6 SAT_6       11
 7 SAT_7       14
 8 SAT_8       10
 9 SAT_9       13
10 SAT_10      14
[1] 14

Both counts give 14 for SAT_7. Those 14 blanks account for the difference between the 503 forms and the 489 nonblank answers for this item.

pl.col(sat_items).is_null().sum() describes the count once. In select(), Polars expands it into one expression per named column. Each expression counts that column’s nulls and gives the result the column’s name.

1
2
blank_counts = survey.select(pl.col(sat_items).is_null().sum())
blank_counts
1
2
3
4
5
6
7
8
shape: (1, 10)
┌───────┬───────┬───────┬───────┬───┬───────┬───────┬───────┬────────┐
│ SAT_1 ┆ SAT_2 ┆ SAT_3 ┆ SAT_4 ┆ … ┆ SAT_7 ┆ SAT_8 ┆ SAT_9 ┆ SAT_10 │
│ ---   ┆ ---   ┆ ---   ┆ ---   ┆   ┆ ---   ┆ ---   ┆ ---   ┆ ---    │
│ u32   ┆ u32   ┆ u32   ┆ u32   ┆   ┆ u32   ┆ u32   ┆ u32   ┆ u32    │
╞═══════╪═══════╪═══════╪═══════╪═══╪═══════╪═══════╪═══════╪════════╡
│ 10    ┆ 10    ┆ 9     ┆ 7     ┆ … ┆ 14    ┆ 10    ┆ 13    ┆ 14     │
└───────┴───────┴───────┴───────┴───┴───────┴───────┴───────┴────────┘

The wide display abbreviates the middle columns with …, although its shape reports all ten. unpivot() makes every item/count pair visible. The two comparisons check that the resulting names match sat_items and that each count equals null_count() applied directly to its source column.

1
2
3
4
blank_long = blank_counts.unpivot(variable_name="item", value_name="n_blank")
blank_long
blank_long["item"].to_list() == sat_items
blank_long["n_blank"].to_list() == [survey[item].null_count() for item in sat_items]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
shape: (10, 2)
┌────────┬─────────┐
│ item   ┆ n_blank │
│ ---    ┆ ---     │
│ str    ┆ u32     │
╞════════╪═════════╡
│ SAT_1  ┆ 10      │
│ SAT_2  ┆ 10      │
│ SAT_3  ┆ 9       │
│ SAT_4  ┆ 7       │
│ SAT_5  ┆ 8       │
│ SAT_6  ┆ 11      │
│ SAT_7  ┆ 14      │
│ SAT_8  ┆ 10      │
│ SAT_9  ┆ 13      │
│ SAT_10 ┆ 14      │
└────────┴─────────┘
True
True

Both comparisons return True. Each displayed count belongs to the intended item and matches its direct calculation.

Counting forms with blank answers

The item counts describe blank cells, but several blanks can belong to one form. How many forms have at least one blank, and how many have all ten items blank?

In dplyr, if_any() tests whether is.na() is true for any selected item on a form. if_all() requires it to be true for all ten. transmute() returns the response ID and these two flags. Each flag is either TRUE or FALSE because is.na() gives a definite result for every entry.

1
2
3
4
5
6
7
blank_flags <- survey |>
  transmute(
    ResponseId,
    any_blank = if_any(all_of(sat_items), is.na),
    all_blank = if_all(all_of(sat_items), is.na)
  )
c(any_blank = sum(blank_flags$any_blank), all_blank = sum(blank_flags$all_blank))
1
2
any_blank all_blank 
       95         0

In Polars, any_horizontal() and all_horizontal() combine the selected null tests across each row. Their names distinguish this direction from .sum() down a column.

1
2
3
4
5
6
blank_flags = survey.select(
    "ResponseId",
    any_blank=pl.any_horizontal(pl.col(sat_items).is_null()),
    all_blank=pl.all_horizontal(pl.col(sat_items).is_null()),
)
blank_flags.select(pl.col("any_blank", "all_blank").sum()).rows()
1
[(95, 0)]

The ten item counts add up to 106 blank cells on 95 forms. A form with two blanks contributes to two item counts but only once to any_blank. No form has all ten items blank.

Mapping the ten items

The same selection of ten columns can be used to transform answers as well as summarize them. Scoring the items applies one label mapping to every selected column. The labels Strongly disagree, Disagree, Neutral, Agree, and Strongly agree correspond to scores from 1 to 5, respectively. The variant Strongly Agree also maps to 5.

In dplyr, across() inside mutate() applies recode_values() to each item through an anonymous function. With .names = "{.col}_score", the results occupy new columns, so the original response text is available for comparison.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
agreement_labels <- c(
  "Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree",
  "Strongly Agree"
)
agreement_scores <- c(1L, 2L, 3L, 4L, 5L, 5L)
sat_mapped <- survey |>
  select(ResponseId, all_of(sat_items)) |>
  mutate(across(
    all_of(sat_items),
    \(x) recode_values(x, from = agreement_labels, to = agreement_scores),
    .names = "{.col}_score"
  ))
dim(sat_mapped)
focal_ids <- c("R_VEMqfh754vZg", "R_NzfZtZHd75Ls", "R_Jkw7hPzsK48Q", "R_aJ8AVumSHlTj")
sat_mapped |>
  filter(ResponseId %in% focal_ids) |>
  select(ResponseId, SAT_7, SAT_7_score, SAT_8, SAT_8_score)
1
2
3
4
5
6
7
8
[1] 503  21
# A tibble: 4 × 5
  ResponseId     SAT_7   SAT_7_score SAT_8             SAT_8_score
  <chr>          <chr>         <int> <chr>                   <int>
1 R_VEMqfh754vZg <NA>             NA Strongly agree              5
2 R_NzfZtZHd75Ls -99              NA Strongly disagree           1
3 R_Jkw7hPzsK48Q Neutral           3 6                          NA
4 R_aJ8AVumSHlTj 0                NA Disagree                    2

The 21 columns are the response ID, ten original items, and ten score columns. In the first two displayed rows, SAT_7_score is NA. The original entries show a blank on the first form and the refusal code -99 on the second. In the third row, Neutral maps to 3 for SAT_7, while the invalid 6 has no score for SAT_8.

In Polars, pl.col(sat_items) expands the calculation across the ten items. replace_strict() maps the labels with the dictionary and returns null for unmapped values because default=None. name.suffix("_score") names the new score columns. Selecting the original items as well lets us see what was recorded for each missing score.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
agreement_scores = {
    "Strongly disagree": 1,
    "Disagree": 2,
    "Neutral": 3,
    "Agree": 4,
    "Strongly agree": 5,
    "Strongly Agree": 5,
}
sat_mapped = survey.select(
    "ResponseId",
    pl.col(sat_items),
    pl.col(sat_items)
    .replace_strict(agreement_scores, default=None)
    .name.suffix("_score"),
)
sat_mapped.shape
focal_ids = ["R_VEMqfh754vZg", "R_NzfZtZHd75Ls", "R_Jkw7hPzsK48Q", "R_aJ8AVumSHlTj"]
sat_mapped.filter(pl.col("ResponseId").is_in(focal_ids)).select(
    "ResponseId", "SAT_7", "SAT_7_score", "SAT_8", "SAT_8_score"
)
1
2
3
4
5
6
7
8
9
10
11
12
(503, 21)
shape: (4, 5)
┌────────────────┬─────────┬─────────────┬───────────────────┬─────────────┐
│ ResponseId     ┆ SAT_7   ┆ SAT_7_score ┆ SAT_8             ┆ SAT_8_score │
│ ---            ┆ ---     ┆ ---         ┆ ---               ┆ ---         │
│ str            ┆ str     ┆ i64         ┆ str               ┆ i64         │
╞════════════════╪═════════╪═════════════╪═══════════════════╪═════════════╡
│ R_VEMqfh754vZg ┆ null    ┆ null        ┆ Strongly agree    ┆ 5           │
│ R_NzfZtZHd75Ls ┆ -99     ┆ null        ┆ Strongly disagree ┆ 1           │
│ R_Jkw7hPzsK48Q ┆ Neutral ┆ 3           ┆ 6                 ┆ null        │
│ R_aJ8AVumSHlTj ┆ 0       ┆ null        ┆ Disagree          ┆ 2           │
└────────────────┴─────────┴─────────────┴───────────────────┴─────────────┘

In the Polars output, Neutral has a score of 3. The blank, the refusal -99, and the invalid codes 6 and 0 all have null scores.

The ten score columns measure agreement with individual items. For SAT_3, SAT_6, and SAT_9, stronger agreement means lower satisfaction, so their scores need to be reversed before the ten items can be combined.

15.4 Applying a calculation to a collection of files

A calculation can vary its input by file path as well as by column name. For the trial exports in data/raw/trials/, one reader can apply the same import choices to several files. The files for sub-006, sub-008, and sub-009 each have a block 1, trial 1. We also need to distinguish those records after the results are combined.

Before using one reader for all three files, we check that the paths exist and that their headers list the same fields. In R, map_chr() collects the three headers in a character vector.

1
2
3
4
5
6
7
8
9
10
paths <- c(
  "data/raw/trials/sub-006_ses-1.csv",
  "data/raw/trials/sub-008_ses-1.csv",
  "data/raw/trials/sub-009_ses-1.csv"
)
paths
file.exists(paths)
headers <- map_chr(paths, \(path) read_lines(path, n_max = 1))
headers[1]
all(headers == headers[1])
1
2
3
4
5
[1] "data/raw/trials/sub-006_ses-1.csv" "data/raw/trials/sub-008_ses-1.csv"
[3] "data/raw/trials/sub-009_ses-1.csv"
[1] TRUE TRUE TRUE
[1] "participant,session,block,trial,trial_type,stim,resp,correct,rt,timestamp,response_json"
[1] TRUE
1
2
3
4
5
6
7
8
9
10
11
12
from pathlib import Path

paths = [
    "data/raw/trials/sub-006_ses-1.csv",
    "data/raw/trials/sub-008_ses-1.csv",
    "data/raw/trials/sub-009_ses-1.csv",
]
paths
[Path(path).exists() for path in paths]
headers = [Path(path).read_text(encoding="utf-8").splitlines()[0] for path in paths]
headers[0]
all([header == headers[0] for header in headers])
1
2
3
4
['data/raw/trials/sub-006_ses-1.csv', 'data/raw/trials/sub-008_ses-1.csv', 'data/raw/trials/sub-009_ses-1.csv']
[True, True, True]
'participant,session,block,trial,trial_type,stim,resp,correct,rt,timestamp,response_json'
True

All three files exist, and all three headers list the same eleven fields in the same order. The reader assigns a type to each field.

Block and trial numbers repeat across participants, and questionnaire records have neither number. The reader therefore adds file, the source file name, and source_row, the record’s position within that file. Numbering starts at 1 for the first record after each header.

In R, trial_types sets the eleven column types. Identifiers, row types, stimuli, responses, timestamps, and questionnaire text are read as text, while session, block, trial, correctness, and response time are integers. read_trial() reads one path with these types, empty fields as NA, and no trimming.

The reader adds file with basename(), the final path component, and source_row with row_number(). .before = 1 places both fields first. map() calls this reader for each path and returns the tables in a list. map_int() with nrow counts their rows before they are combined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
trial_types <- cols(
  participant = col_character(),
  session = col_integer(),
  block = col_integer(),
  trial = col_integer(),
  trial_type = col_character(),
  stim = col_character(),
  resp = col_character(),
  correct = col_integer(),
  rt = col_integer(),
  timestamp = col_character(),
  response_json = col_character()
)
read_trial <- function(path) {
  read_csv(path, col_types = trial_types, na = "", trim_ws = FALSE) |>
    mutate(file = basename(path), source_row = row_number(), .before = 1)
}
trial_tables <- map(paths, read_trial)
tibble(file = basename(paths), rows = map_int(trial_tables, nrow))
1
2
3
4
5
6
# A tibble: 3 × 2
  file               rows
  <chr>             <int>
1 sub-006_ses-1.csv   201
2 sub-008_ses-1.csv   201
3 sub-009_ses-1.csv   201

Each file contributes 201 records. dplyr::bind_rows() stacks the three tables by column name. After stacking, where does block 1, trial 1 appear for each participant? The final counts compare the combined row count with the sum of the three file counts and the number of distinct pairs of file and source_row.

1
2
3
4
5
6
7
8
9
10
11
trials <- bind_rows(trial_tables)
trials |>
  filter(block == 1, trial == 1) |>
  select(file, source_row, participant, block, trial, rt)
count(trials, file)
count(trials, file, trial_type)
c(
  combined = nrow(trials),
  contributors = sum(map_int(trial_tables, nrow)),
  sources = n_distinct(trials$file, trials$source_row)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# A tibble: 3 × 6
  file              source_row participant block trial    rt
  <chr>                  <int> <chr>       <int> <int> <int>
1 sub-006_ses-1.csv          9 sub-006         1     1   826
2 sub-008_ses-1.csv          9 sub-008         1     1   504
3 sub-009_ses-1.csv          9 sub-009         1     1   592
# A tibble: 3 × 2
  file                  n
  <chr>             <int>
1 sub-006_ses-1.csv   201
2 sub-008_ses-1.csv   201
3 sub-009_ses-1.csv   201
# A tibble: 6 × 3
  file              trial_type     n
  <chr>             <chr>      <int>
1 sub-006_ses-1.csv keyboard     200
2 sub-006_ses-1.csv survey         1
3 sub-008_ses-1.csv keyboard     200
4 sub-008_ses-1.csv survey         1
5 sub-009_ses-1.csv keyboard     200
6 sub-009_ses-1.csv survey         1
    combined contributors      sources 
         603          603          603 

Block 1, trial 1 is the ninth record in each file, after eight practice trials. For sub-006, that record gives a response time of 826 milliseconds. The 603 combined rows have 603 distinct file and row pairs. Each file contributes eight practice trials, 192 test trials, and one questionnaire.

In Python, trial_schema maps the eleven field names to their Polars types. Passing it as schema to pl.read_csv() sets all names and types. Polars matches the fields by name, so their order in the file may differ. A missing or unexpected field name raises a SchemaError.

with_row_index("source_row", offset=1) numbers records from 1, and pl.lit(Path(path).name) adds the file name. A comprehension calls this reader for each path and collects the three returned tables in a list.

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
trial_schema = {
    "participant": pl.String,
    "session": pl.Int64,
    "block": pl.Int64,
    "trial": pl.Int64,
    "trial_type": pl.String,
    "stim": pl.String,
    "resp": pl.String,
    "correct": pl.Int64,
    "rt": pl.Int64,
    "timestamp": pl.String,
    "response_json": pl.String,
}


def read_trial(path):
    return (
        pl.read_csv(path, schema=trial_schema)
        .with_row_index("source_row", offset=1)
        .with_columns(file=pl.lit(Path(path).name))
    )


trial_tables = [read_trial(path) for path in paths]
[(table["file"][0], table.height) for table in trial_tables]
1
[('sub-006_ses-1.csv', 201), ('sub-008_ses-1.csv', 201), ('sub-009_ses-1.csv', 201)]

Each file contributes 201 records. pl.concat(..., how="vertical") stacks the tables with matching columns in matching order. Block 1 trial 1 occurs in all three files. The file and source-row pairs should distinguish all 603 records, including the questionnaires.

1
2
3
4
5
6
7
8
9
10
11
trials = pl.concat(trial_tables, how="vertical")
trials.filter((pl.col("block") == 1) & (pl.col("trial") == 1)).select(
    "file", "source_row", "participant", "block", "trial", "rt"
)
trials.group_by("file").agg(n=pl.len()).sort("file")
trials.group_by("file", "trial_type").agg(n=pl.len()).sort("file", "trial_type")
(
    trials.height,
    sum(table.height for table in trial_tables),
    trials.select("file", "source_row").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
25
26
27
28
29
30
31
32
33
34
shape: (3, 6)
┌───────────────────┬────────────┬─────────────┬───────┬───────┬─────┐
│ file              ┆ source_row ┆ participant ┆ block ┆ trial ┆ rt  │
│ ---               ┆ ---        ┆ ---         ┆ ---   ┆ ---   ┆ --- │
│ str               ┆ u32        ┆ str         ┆ i64   ┆ i64   ┆ i64 │
╞═══════════════════╪════════════╪═════════════╪═══════╪═══════╪═════╡
│ sub-006_ses-1.csv ┆ 9          ┆ sub-006     ┆ 1     ┆ 1     ┆ 826 │
│ sub-008_ses-1.csv ┆ 9          ┆ sub-008     ┆ 1     ┆ 1     ┆ 504 │
│ sub-009_ses-1.csv ┆ 9          ┆ sub-009     ┆ 1     ┆ 1     ┆ 592 │
└───────────────────┴────────────┴─────────────┴───────┴───────┴─────┘
shape: (3, 2)
┌───────────────────┬─────┐
│ file              ┆ n   │
│ ---               ┆ --- │
│ str               ┆ u32 │
╞═══════════════════╪═════╡
│ sub-006_ses-1.csv ┆ 201 │
│ sub-008_ses-1.csv ┆ 201 │
│ sub-009_ses-1.csv ┆ 201 │
└───────────────────┴─────┘
shape: (6, 3)
┌───────────────────┬────────────┬─────┐
│ file              ┆ trial_type ┆ n   │
│ ---               ┆ ---        ┆ --- │
│ str               ┆ str        ┆ u32 │
╞═══════════════════╪════════════╪═════╡
│ sub-006_ses-1.csv ┆ keyboard   ┆ 200 │
│ sub-006_ses-1.csv ┆ survey     ┆ 1   │
│ sub-008_ses-1.csv ┆ keyboard   ┆ 200 │
│ sub-008_ses-1.csv ┆ survey     ┆ 1   │
│ sub-009_ses-1.csv ┆ keyboard   ┆ 200 │
│ sub-009_ses-1.csv ┆ survey     ┆ 1   │
└───────────────────┴────────────┴─────┘
(603, 603, 603)

The first test trial is record 9 in each file. Its response time is 826 milliseconds for sub-006, 504 for sub-008, and 592 for sub-009. All 603 records have a distinct file and row pair. Each file contains eight keyboard practice trials in block 0, 192 keyboard test trials in the four test blocks, and one questionnaire.

Paths without records

Another export in this folder, sub-041_ses-1.csv, is zero bytes long. Reading it separately with readr::read_csv() and trial_types returns zero rows and warns that the named columns are absent. With trial_schema, pl.read_csv() raises NoDataError. The three paths show that this file was outside the batch. From the 603 combined rows alone, we could not distinguish a skipped file from one that returned no records.

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