From Recorded Numbers to Usable Measurements
A program can read the survey’s refusal code -99 as an integer, but including it in a satisfaction mean would give a nonresponse the meaning of a score. Preparing numbers for analysis therefore requires more than successful conversion from text. We need to establish which values are valid measurements and which observations contribute to each calculation. This chapter moves from parsing numeric text and checking valid ranges to recording missingness and defining summary denominators. We then reverse scores, change units, and transform measurements, examining how each operation affects the meaning of the result.
10.1 Parsing numbers and checking their domain
Suppose a survey export records a completion duration as "1,234" seconds. This string is constructed for the example, since the supplied survey does not insert grouping commas. If the comma separates thousands, the duration is 1234 seconds. If it is a decimal mark, the same text means 1.234 seconds. Parsing converts text to a number under the source’s stated convention. Here the comma separates thousands.
readr::parse_number() reads a number from text, even with surrounding characters such as a currency sign. The locale argument specifies how to read the punctuation. The first call uses grouping_mark = "," for a thousands separator. The second uses decimal_mark = "," for a decimal comma.
1
2
3
4
5
6
7
8
library(tidyverse)
duration_text <- "1,234"
duration <- parse_number(duration_text, locale = locale(grouping_mark = ","))
duration_text
duration
typeof(duration)
parse_number(duration_text, locale = locale(decimal_mark = ",", grouping_mark = "."))
1
2
3
4
[1] "1,234"
[1] 1234
[1] "double"
[1] 1.234
Both calls read "1,234". With a thousands separator, the result is the double 1234. With a decimal comma, it is 1.234. A successful parse alone cannot tell us which duration the source intended.
Casting converts a value to another type. Which numbers can R store unchanged as integers? The three inputs to as.integer() are duration, the fraction 2.7 and 3e9, scientific notation for three billion.
1
2
3
as.integer(duration)
as.integer(2.7)
as.integer(3e9)
1
2
3
4
5
[1] 1234
[1] 2
[1] NA
Warning message:
NAs introduced by coercion to integer range
The integer cast returns 1234 unchanged and truncates 2.7 to 2 without a warning. Three billion exceeds the integer range, so as.integer() returns NA and issues a warning.
In durations, the completion time is a string with a thousands separator.
1
2
3
import polars as pl
durations = pl.DataFrame({"duration_text": ["1,234"]})
The Polars cast() method has no setting for a thousands separator. What happens if it tries to read "1,234" directly as an integer?
1
2
# Deliberate error: a direct cast of text that contains a grouping comma
durations.with_columns(duration=pl.col("duration_text").cast(pl.Int64))
1
polars.exceptions.InvalidOperationError: conversion from `str` to `i64` failed in column 'duration_text' for 1 out of 1 values: ["1,234"]
The comma prevents a direct cast. Because it separates thousands here, str.replace_all(",", "", literal=True) removes it before cast(pl.Int64) converts the digits to an integer.
1
2
3
4
5
6
durations = durations.with_columns(
duration=pl.col("duration_text")
.str.replace_all(",", "", literal=True)
.cast(pl.Int64)
)
durations
1
2
3
4
5
6
7
8
shape: (1, 2)
┌───────────────┬──────────┐
│ duration_text ┆ duration │
│ --- ┆ --- │
│ str ┆ i64 │
╞═══════════════╪══════════╡
│ 1,234 ┆ 1234 │
└───────────────┴──────────┘
The row shows 1,234 as text beside the integer 1234. Had the comma been a decimal mark, removing it would have turned 1.234 seconds into 1234 seconds.
dtype reports the data type after the cast to Int32. The other examples test two limits of integer conversion. What happens to the fractional part of 2.7, and what happens to 300 when the target is Int8, an eight-bit integer type with values from -128 to 127?
1
2
3
durations["duration"].cast(pl.Int32).dtype
pl.Series([2.7]).cast(pl.Int64).to_list()
pl.Series([300]).cast(pl.Int8, strict=False).to_list()
1
2
3
Int32
[2]
[None]
1
2
# Deliberate error: a value outside the range of Int8
pl.Series([300]).cast(pl.Int8)
1
polars.exceptions.InvalidOperationError: conversion from `i64` to `i8` failed in column '' for 1 out of 1 values: [300]
The duration fits Int32. The fractional cast truncates 2.7 to 2 without an error, so a successful cast does not show that the value is unchanged. The out-of-range 300 raises an error under the default strict cast and becomes null with strict=False.
Domain rules
An item’s domain is the set of values it allows. An integer column can store 0, but what would 0 mean here? The survey agreement scale starts at 1. On the panel’s depression and anxiety items, 0 is a valid answer meaning Not at all. Table 10.1 gives the allowed scores for each.
Table 10.1. Valid codes for two kinds of questionnaire item.
| Item | Valid values | Code 0 | Code 6 |
|---|---|---|---|
| Survey agreement item | whole numbers from 1 to 5 | Invalid | Invalid |
| Panel depression or anxiety item | whole numbers from 0 to 3 | Valid | Invalid |
Three constructed survey records contain "3", "6" and "unknown". readr::parse_integer() expects whole-number text. A TRUE in parsed means the text yielded an integer. A TRUE in in_domain means that integer is also between 1 and 5.
1
2
3
4
5
6
7
8
recorded <- tibble(source_id = c("v1", "v2", "v3"), recorded = c("3", "6", "unknown"))
checked <- recorded |>
mutate(value = parse_integer(recorded)) |>
mutate(
parsed = !is.na(value),
in_domain = parsed & value >= 1 & value <= 5
)
checked
1
2
3
4
5
6
7
8
9
10
11
12
13
Warning message:
There was 1 warning in `mutate()`.
ℹ In argument: `value = parse_integer(recorded)`.
Caused by warning:
! 1 parsing failure.
row col expected actual
3 -- no trailing characters unknown
# A tibble: 3 × 5
source_id recorded value parsed in_domain
<chr> <chr> <int> <lgl> <lgl>
1 v1 3 3 TRUE TRUE
2 v2 6 6 TRUE FALSE
3 v3 unknown NA FALSE FALSE
v1 passes both checks. v2 parses to 6 but is outside the domain. v3 triggers a parsing warning and has no number, so its domain flag is false as well. The parsed flag tells those last two cases apart.
In Polars, cast(pl.Int64, strict=False) gives null when recorded text cannot be read as an integer. Both checks refer to the parsed value. is_between(1, 5) includes both endpoints but returns null for a null input. Combining it with is_not_null() using & makes in_domain false for that case.
1
2
3
4
5
6
7
8
9
10
recorded = pl.DataFrame(
{"source_id": ["v1", "v2", "v3"], "recorded": ["3", "6", "unknown"]}
)
checked = recorded.with_columns(
value=pl.col("recorded").cast(pl.Int64, strict=False)
).with_columns(
parsed=pl.col("value").is_not_null(),
in_domain=pl.col("value").is_not_null() & pl.col("value").is_between(1, 5),
)
checked
1
2
3
4
5
6
7
8
9
10
shape: (3, 5)
┌───────────┬──────────┬───────┬────────┬───────────┐
│ source_id ┆ recorded ┆ value ┆ parsed ┆ in_domain │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ bool ┆ bool │
╞═══════════╪══════════╪═══════╪════════╪═══════════╡
│ v1 ┆ 3 ┆ 3 ┆ true ┆ true │
│ v2 ┆ 6 ┆ 6 ┆ true ┆ false │
│ v3 ┆ unknown ┆ null ┆ false ┆ false │
└───────────┴──────────┴───────┴────────┴───────────┘
For v2, parsed is true and in_domain is false. The number 6 is therefore available for arithmetic even though it is outside the survey scale. For v3, the text "unknown" produced no number at all.
Storage range and arithmetic
Even when each input is valid, its storage type may be too narrow to represent the result of an arithmetic operation. Nine minutes is 540 seconds. Both inputs to the multiplication, 9 and 60, fit in Int8, but their product does not. The three Polars expressions show what happens when multiplication uses Int8, when both operands are widened to Int16 first, and when only the product is widened.
1
2
3
4
5
6
7
8
9
10
factors = pl.DataFrame(
{"minutes": [9], "seconds_per_minute": [60]},
schema={"minutes": pl.Int8, "seconds_per_minute": pl.Int8},
)
factors.select(
narrow=pl.col("minutes") * pl.col("seconds_per_minute"),
widened=pl.col("minutes").cast(pl.Int16)
* pl.col("seconds_per_minute").cast(pl.Int16),
cast_after=(pl.col("minutes") * pl.col("seconds_per_minute")).cast(pl.Int16),
)
1
2
3
4
5
6
7
8
shape: (1, 3)
┌────────┬─────────┬────────────┐
│ narrow ┆ widened ┆ cast_after │
│ --- ┆ --- ┆ --- │
│ i8 ┆ i16 ┆ i16 │
╞════════╪═════════╪════════════╡
│ 28 ┆ 540 ┆ 28 │
└────────┴─────────┴────────────┘
The narrow product is 28, with no warning or error. It wrapped around the 256 values of Int8. Subtracting 256 twice from 540 gives 28. Widening both operands gives 540, which fits Int16’s upper bound of 32,767. Widening after multiplication still gives 28 because the original result has already been lost.
R’s ordinary integers have a larger range. The suffix L makes 9L * 60L an integer multiplication. Adding 1L to .Machine$integer.max, the largest ordinary integer, shows what happens just beyond that range.
1
2
3
.Machine$integer.max
9L * 60L
.Machine$integer.max + 1L
1
2
3
4
5
[1] 2147483647
[1] 540
[1] NA
Warning message:
In .Machine$integer.max + 1L : NAs produced by integer overflow
The multiplication gives 540 with R’s ordinary integers. Adding 1 to their largest value, 2,147,483,647, gives NA with a warning. In the Polars Int8 example, the product exceeded the range and returned 28 without a warning.
10.2 Missing values and reasons for missingness
Four constructed forms record "2", a blank, "-99" and "6" for a survey item scored from 1 to 5. Only the first answer has a score. The blank means the item was skipped, -99 records a refusal, and 6 is outside the scale. A reason beside each missing score tells these three cases apart.
After parsing, both -99 and 6 fall outside the range. dplyr::case_when() first checks the recorded answer for a blank or the refusal code "-99". For any other answer, a failed parse or an out-of-range number gives the reason invalid. if_else() assigns the parsed value to score for an observed answer and NA_integer_ otherwise. The type checks compare this integer missing value with plain NA and with score.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
answers <- tibble(
response_id = c("r1", "r2", "r3", "r4"),
recorded = c("2", NA, "-99", "6")
)
coded <- answers |>
mutate(value = parse_integer(recorded)) |>
mutate(
reason = case_when(
is.na(recorded) ~ "skipped",
recorded == "-99" ~ "refused",
is.na(value) | value < 1 | value > 5 ~ "invalid",
.default = "observed"
)
) |>
mutate(score = if_else(reason == "observed", value, NA_integer_))
coded
c(typeof(NA), typeof(NA_integer_), typeof(coded$score))
1
2
3
4
5
6
7
8
# A tibble: 4 × 5
response_id recorded value reason score
<chr> <chr> <int> <chr> <int>
1 r1 2 2 observed 2
2 r2 <NA> NA skipped NA
3 r3 -99 -99 refused NA
4 r4 6 6 invalid NA
[1] "logical" "integer" "integer"
Only r1 has a score. The reason column distinguishes the three missing scores, and the type checks show that plain NA is logical while NA_integer_ and score are integer.
How does a missing score compare with an undefined calculation? In each test below, r3’s score comes first and the result of 0 / 0 comes second.
1
2
3
4
undefined <- 0 / 0
undefined
is.na(c(coded$score[3], undefined))
is.nan(c(coded$score[3], undefined))
1
2
3
[1] NaN
[1] TRUE TRUE
[1] FALSE TRUE
R returns NaN (Not a Number) for 0 / 0. is.na() is true for both r3’s missing score and the undefined result. Only the second value gives TRUE with is.nan(). The refused label records why r3 has no score.
In Polars, None represents the blank and cast(pl.Int64, strict=False) parses the text. A refusal would also fail the range test, so skipped and refused answers need their own branches first. For the remaining answers, is_null() detects a failed parse, and ~ negates is_between(1, 5) to flag numbers outside the scale. pl.lit() writes each reason as text. The final pl.when() gives observed answers their parsed scores. Without .otherwise(), the other rows receive null.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
answers = pl.DataFrame(
{"response_id": ["r1", "r2", "r3", "r4"], "recorded": ["2", None, "-99", "6"]}
)
coded = (
answers.with_columns(value=pl.col("recorded").cast(pl.Int64, strict=False))
.with_columns(
reason=pl.when(pl.col("recorded").is_null())
.then(pl.lit("skipped"))
.when(pl.col("recorded") == "-99")
.then(pl.lit("refused"))
.when(pl.col("value").is_null() | ~pl.col("value").is_between(1, 5))
.then(pl.lit("invalid"))
.otherwise(pl.lit("observed"))
)
.with_columns(score=pl.when(pl.col("reason") == "observed").then(pl.col("value")))
)
coded
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 5)
┌─────────────┬──────────┬───────┬──────────┬───────┐
│ response_id ┆ recorded ┆ value ┆ reason ┆ score │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str ┆ i64 │
╞═════════════╪══════════╪═══════╪══════════╪═══════╡
│ r1 ┆ 2 ┆ 2 ┆ observed ┆ 2 │
│ r2 ┆ null ┆ null ┆ skipped ┆ null │
│ r3 ┆ -99 ┆ -99 ┆ refused ┆ null │
│ r4 ┆ 6 ┆ 6 ┆ invalid ┆ null │
└─────────────┴──────────┴───────┴──────────┴───────┘
The integer score column has three nulls, with their different causes recorded in reason.
How does the null for r3 compare with the result of dividing zero by zero? pl.select() evaluates the division without an input table, and ["undefined"][0] retrieves the result. In the Float64 series mixed, the first value is the missing score and the second is the result of the division.
1
2
3
4
5
undefined = pl.select(undefined=pl.lit(0.0) / pl.lit(0.0))["undefined"][0]
undefined
mixed = pl.Series("x", [coded["score"][2], undefined], dtype=pl.Float64)
mixed.is_null().to_list()
mixed.is_nan().to_list()
1
2
3
nan
[True, False]
[None, True]
1
2
# Deliberate error: ordinary Python division of zero by zero
0.0 / 0.0
1
ZeroDivisionError: division by zero
In the Polars result, is_null() identifies the missing survey score. is_nan() returns null for that score and True for the NaN (Not a Number) produced by the division. Python’s own 0.0 / 0.0 raises ZeroDivisionError. The refused label for r3 comes from the original survey code.
Filling the three unavailable scores with 0 would produce 2, 0, 0, 0, adding measurements that were never recorded. Zero is outside this survey scale and means Not at all on the panel scale.
10.3 Missing values in sums, means, and denominators
Suppose an item has scores of 2 and 4 on two forms and is blank on a third. What mean can we report? We can average the two observed scores. The records cannot tell us what the mean would have been if all three forms had included a score.
The two scores sum to 6, so their mean is 6 / 2 = 3. Dividing by all three forms would give 2, just as if the blank had been scored zero.
For R’s sum() and mean(), na.rm = TRUE removes missing values before calculation. sum(!is.na(values)) counts the positions that then contribute to both the total and the mean.
1
2
3
4
5
6
7
values <- c(2, 4, NA)
c(sum(values), mean(values))
c(
n_observed = sum(!is.na(values)),
sum = sum(values, na.rm = TRUE),
mean = mean(values, na.rm = TRUE)
)
1
2
3
[1] NA NA
n_observed sum mean
2 6 3
With the defaults, both results are NA. With na.rm = TRUE, the sum is 6 and the mean is 3. The count of 2 gives the denominator for that mean.
The empty vector has no entries. The second vector has two entries, both NA_real_, the missing value for a double. Neither contains a score to average. observed_mean() returns NA_real_ when the count of observed scores is zero.
1
2
3
4
5
6
7
8
9
10
11
12
empty <- numeric(0)
all_missing <- c(NA_real_, NA_real_)
c(sum(empty), mean(empty))
c(sum(all_missing, na.rm = TRUE), mean(all_missing, na.rm = TRUE))
observed_mean <- function(x) {
if (sum(!is.na(x)) > 0) {
mean(x, na.rm = TRUE)
} else {
NA_real_
}
}
c(observed_mean(values), observed_mean(empty), observed_mean(all_missing))
1
2
3
[1] 0 NaN
[1] 0 NaN
[1] 3 NA NA
The sum of no observed values is zero. This is the result of the sum operation, even though no form recorded a zero. The denominator for the mean is also 0, so mean() gives NaN here. observed_mean() reports NA for both cases and 3 for the two observed scores.
The Polars Float64 series has three positions, containing 2.0, 4.0 and null. len() counts positions, while the Series method count() counts the non-null values available to sum() and mean().
1
2
values = pl.Series("value", [2.0, 4.0, None], dtype=pl.Float64)
(len(values), values.count(), values.sum(), values.mean())
1
(3, 2, 6.0, 3.0)
The series has three positions and two observed scores. By default, Polars skips nulls, giving a sum of 6.0 and a mean of 3.0.
An empty series and an all-null series have no observed scores. A third series contains 2.0, 4.0 and NaN. Does the default mean treat NaN like a null? For the mean we report, observed_mean() excludes both with drop_nulls() and drop_nans() and returns None if there are no values to average.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
empty = pl.Series("value", [], dtype=pl.Float64)
all_null = pl.Series("value", [None, None], dtype=pl.Float64)
[(series.count(), series.sum(), series.mean()) for series in [empty, all_null]]
with_nan = pl.Series("value", [2.0, 4.0, float("nan")], dtype=pl.Float64)
(with_nan.count(), with_nan.sum(), with_nan.mean())
def observed_mean(series):
contributing = series.drop_nulls().drop_nans()
if len(contributing) > 0:
return contributing.mean()
return None
[observed_mean(series) for series in [values, empty, all_null, with_nan]]
1
2
3
[(0, 0.0, None), (0, 0.0, None)]
(3, nan, nan)
[3.0, None, None, 3.0]
The empty and all-null series each have a sum of 0.0 and a mean of None. The zero sum does not represent an observed score. In the third series, count() includes NaN, giving 3, and the default sum and mean are both nan.
After observed_mean() excludes NaN, only 2 and 4 contribute, so the reported mean is 3.0. The function defines which values enter this mean; it does not explain why a NaN occurred. That requires examining the calculation that produced it.
Summarizing a survey item
In the survey file, SAT_1 records agreement with “I am mostly satisfied with my life right now.” The labels Strongly disagree, Disagree, Neutral, Agree and Strongly agree score from 1 to 5, respectively. A recognized label counts as observed, a blank as skipped, -99 as refused and any other entry as invalid. Each submitted form counts once, and only observed scores enter the item mean.
readr::read_csv() reads the item as text and an empty field as NA. dplyr::recode_values() maps the five labels to 1:5, returning NA for other entries. case_when() checks the recorded SAT_1 for a blank or refusal before classifying any other answer without a score as invalid.
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
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")
)
agreement_levels <- c(
"Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"
)
sat_1 <- survey |>
select(ResponseId, SAT_1) |>
mutate(score = recode_values(SAT_1, from = agreement_levels, to = 1:5)) |>
mutate(
reason = case_when(
is.na(SAT_1) ~ "skipped",
SAT_1 == "-99" ~ "refused",
is.na(score) ~ "invalid",
.default = "observed"
)
)
count(sat_1, reason)
sat_1 |>
summarise(
n_responses = n(),
n_contributing = sum(reason == "observed"),
n_unavailable = sum(reason != "observed"),
total = sum(score, na.rm = TRUE),
mean = observed_mean(score)
)
1
2
3
4
5
6
7
8
9
10
# A tibble: 3 × 2
reason n
<chr> <int>
1 observed 492
2 refused 1
3 skipped 10
# A tibble: 1 × 5
n_responses n_contributing n_unavailable total mean
<int> <int> <int> <int> <dbl>
1 503 492 11 1633 3.32
Of the 503 submissions, 492 have a score for SAT_1. Their scores sum to 1,633, so the mean is 1,633 / 492, displayed as 3.32. The ten skips and one refusal explain the other 11 rows. There are no invalid answers for this item.
pl.read_csv() reads SAT_1 as text and empty fields as null. replace_strict() uses agreement_scores to map the five labels, with default=None for other entries. The reason column distinguishes skips, refusals and invalid entries. pl.len() counts every submission, while observed_mean() averages the available scores.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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",
)
agreement_scores = {
"Strongly disagree": 1,
"Disagree": 2,
"Neutral": 3,
"Agree": 4,
"Strongly agree": 5,
}
sat_1 = (
survey.select("ResponseId", "SAT_1")
.with_columns(score=pl.col("SAT_1").replace_strict(agreement_scores, default=None))
.with_columns(
reason=pl.when(pl.col("SAT_1").is_null())
.then(pl.lit("skipped"))
.when(pl.col("SAT_1") == "-99")
.then(pl.lit("refused"))
.when(pl.col("score").is_null())
.then(pl.lit("invalid"))
.otherwise(pl.lit("observed"))
)
)
sat_1.group_by("reason").agg(n=pl.len()).sort("reason")
sat_1.select(
n_responses=pl.len(),
n_contributing=(pl.col("reason") == "observed").sum(),
n_unavailable=(pl.col("reason") != "observed").sum(),
total=pl.col("score").sum(),
)
observed_mean(sat_1["score"])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
shape: (3, 2)
┌──────────┬─────┐
│ reason ┆ n │
│ --- ┆ --- │
│ str ┆ u32 │
╞══════════╪═════╡
│ observed ┆ 492 │
│ refused ┆ 1 │
│ skipped ┆ 10 │
└──────────┴─────┘
shape: (1, 4)
┌─────────────┬────────────────┬───────────────┬───────┐
│ n_responses ┆ n_contributing ┆ n_unavailable ┆ total │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 ┆ i64 │
╞═════════════╪════════════════╪═══════════════╪═══════╡
│ 503 ┆ 492 ┆ 11 ┆ 1633 │
└─────────────┴────────────────┴───────────────┴───────┘
3.319105691056911
The 492 scored answers, ten skips and one refusal account for all 503 submissions. The displayed mean is 1,633 divided by 492. The R tibble rounds that same value to 3.32.
10.4 Transforming measurements while retaining their meaning
The statement for SAT_3 is “These days I am dissatisfied with my life.” Strong agreement indicates low satisfaction on this item and high satisfaction on SAT_1. Reversing the valid SAT_3 scores makes a high score mean greater satisfaction on both items. The eight constructed records use the five scores, a blank, the refusal code -99 and an invalid 6.
On this scale, 1 pairs with 5, 2 with 4 and 3 with itself. Each pair sums to 6, the sum of the endpoints, so a valid score x reverses to 6 - x. On a scale from 0 to 3, the endpoint sum would instead give 3 - x.
In item_scores, value is the parsed number and score is the validated item score. Only observed answers have a numeric score. The reversal uses 6L - score, so a missing score gives a missing result. The L makes 6 an integer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
item <- tibble(
response_id = c("s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"),
recorded = c("1", "2", "3", "4", "5", NA, "-99", "6")
)
item_scores <- item |>
mutate(value = parse_integer(recorded)) |>
mutate(
reason = case_when(
is.na(recorded) ~ "skipped",
recorded == "-99" ~ "refused",
is.na(value) | value < 1 | value > 5 ~ "invalid",
.default = "observed"
)
) |>
mutate(score = if_else(reason == "observed", value, NA_integer_)) |>
mutate(reversed = 6L - score)
item_scores
1
2
3
4
5
6
7
8
9
10
11
# A tibble: 8 × 6
response_id recorded value reason score reversed
<chr> <chr> <int> <chr> <int> <int>
1 s1 1 1 observed 1 5
2 s2 2 2 observed 2 4
3 s3 3 3 observed 3 3
4 s4 4 4 observed 4 2
5 s5 5 5 observed 5 1
6 s6 <NA> NA skipped NA NA
7 s7 -99 -99 refused NA NA
8 s8 6 6 invalid NA NA
The five valid scores reverse to 5, 4, 3, 2 and 1. For the other three forms, both score and reversed are NA. What would the formula return if it used value, where s7 has -99 and s8 has 6?
1
6L - item_scores$value
1
[1] 5 4 3 2 1 NA 105 0
Applied to value, the formula gives 105 for the refusal on s7 and 0 for the invalid answer on s8. Applied to score, it gives NA for both. For s5, strong agreement with dissatisfaction reverses from 5 to 1. This is a score on one item. A satisfaction scale score would combine several items that measure satisfaction.
In Polars, cast(pl.Int64, strict=False) reads the numeric text, including the refusal code. The conditions identify skipped, refused and invalid answers before classifying an answer as observed. Only observed answers receive a numeric score. Subtracting that column from 6 gives null for each unavailable score.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
item = pl.DataFrame(
{
"response_id": ["s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"],
"recorded": ["1", "2", "3", "4", "5", None, "-99", "6"],
}
)
item_scores = (
item.with_columns(value=pl.col("recorded").cast(pl.Int64, strict=False))
.with_columns(
reason=pl.when(pl.col("recorded").is_null())
.then(pl.lit("skipped"))
.when(pl.col("recorded") == "-99")
.then(pl.lit("refused"))
.when(pl.col("value").is_null() | ~pl.col("value").is_between(1, 5))
.then(pl.lit("invalid"))
.otherwise(pl.lit("observed"))
)
.with_columns(score=pl.when(pl.col("reason") == "observed").then(pl.col("value")))
.with_columns(reversed=6 - pl.col("score"))
)
item_scores
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
shape: (8, 6)
┌─────────────┬──────────┬───────┬──────────┬───────┬──────────┐
│ response_id ┆ recorded ┆ value ┆ reason ┆ score ┆ reversed │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ str ┆ i64 ┆ i64 │
╞═════════════╪══════════╪═══════╪══════════╪═══════╪══════════╡
│ s1 ┆ 1 ┆ 1 ┆ observed ┆ 1 ┆ 5 │
│ s2 ┆ 2 ┆ 2 ┆ observed ┆ 2 ┆ 4 │
│ s3 ┆ 3 ┆ 3 ┆ observed ┆ 3 ┆ 3 │
│ s4 ┆ 4 ┆ 4 ┆ observed ┆ 4 ┆ 2 │
│ s5 ┆ 5 ┆ 5 ┆ observed ┆ 5 ┆ 1 │
│ s6 ┆ null ┆ null ┆ skipped ┆ null ┆ null │
│ s7 ┆ -99 ┆ -99 ┆ refused ┆ null ┆ null │
│ s8 ┆ 6 ┆ 6 ┆ invalid ┆ null ┆ null │
└─────────────┴──────────┴───────┴──────────┴───────┴──────────┘
The five valid scores reverse to 5, 4, 3, 2 and 1. A skip, a refusal and an invalid answer each have a null in reversed. Their original codes are in recorded, and their parsed numbers, if any, are in value.
1
(6 - item_scores["value"]).to_list()
1
[5, 4, 3, 2, 1, None, 105, 0]
Without validation, the refusal becomes 105 and the invalid 6 becomes 0. Both are ordinary numbers that later arithmetic would accept. Reversing the validated scores twice should restore score. The Series method equals() checks that the values agree, including nulls in corresponding positions.
1
(6 - item_scores["reversed"]).equals(item_scores["score"])
1
True
The second reversal restores score, including its nulls. But two reversals would also take -99 to 105 and back to -99. Checking which answers qualify as scores is what excludes the refusal. A higher reversed SAT_3 score indicates greater satisfaction on this item. A satisfaction scale score would combine several items that measure satisfaction.
Units, origins, and domains
Reversing an item score changes which end of the scale indicates greater satisfaction. Other transformations change a measurement’s unit or the point from which it is measured. Thirty seconds is half a minute. Measured from a 30-second reference, the same duration gives a difference of zero. Three constructed durations, 15, 30 and 90 seconds, illustrate the change of unit and the change of origin.
Dividing seconds by 60 expresses each duration in minutes. mutate() adds minutes beside seconds in times.
1
2
3
times <- tibble(response_id = c("r1", "r2", "r3"), seconds = c(15, 30, 90))
times <- mutate(times, minutes = seconds / 60)
times
1
2
3
4
5
6
# A tibble: 3 × 3
response_id seconds minutes
<chr> <dbl> <dbl>
1 r1 15 0.25
2 r2 30 0.5
3 r3 90 1.5
The durations are 0.25, 0.5 and 1.5 minutes, in the same order. Dividing by 60 also maps zero seconds to zero minutes.
minutes - 0.5 gives the difference from the half-minute reference in minutes.
1
2
reference_minutes <- 0.5
mutate(times, from_reference_minutes = minutes - reference_minutes)
1
2
3
4
5
6
# A tibble: 3 × 4
response_id seconds minutes from_reference_minutes
<chr> <dbl> <dbl> <dbl>
1 r1 15 0.25 -0.25
2 r2 30 0.5 0
3 r3 90 1.5 1
For r1, -0.25 minutes means 15 seconds shorter than the reference. For r2, zero means the duration was exactly 30 seconds. For r3, the duration was one minute longer than the reference.
To compare durations by their ratios, we can take logarithms and subtract the results. The natural logarithm of a positive number is the power to which the constant e, about 2.718, must be raised to produce that number. All three durations in minutes fall within the domain of the logarithm: the positive inputs for which it gives a finite real value.
Changing the origin changes the inputs to that transformation. After subtracting half a minute, only one difference is positive. The calls below compare logarithms of the original durations with logarithms of the shifted values. The last call uses if_else() to mark the two nonpositive differences as NA_real_ before taking the log.
1
2
3
4
5
minutes <- times$minutes
from_reference <- minutes - reference_minutes
log(minutes)
log(from_reference)
log(if_else(from_reference > 0, from_reference, NA_real_))
1
2
3
4
5
[1] -1.3862944 -0.6931472 0.4054651
[1] NaN -Inf 0
Warning message:
In log(from_reference) : NaNs produced
[1] NA NA 0
The logs of 0.25 and 0.5 are negative because both numbers lie between 0 and 1. The log values are no longer durations in minutes. Subtracting log(0.25) from log(0.5) gives log(2) because 30 seconds is twice 15 seconds.
For the differences from the reference, log() gives NaN with a warning for -0.25 and -Inf for zero. The only finite result is log(1) = 0 for r3, whose duration was one minute above the reference.
In times.with_columns(), dividing pl.col("seconds") by 60 adds a minutes column beside seconds.
1
2
3
times = pl.DataFrame({"response_id": ["r1", "r2", "r3"], "seconds": [15, 30, 90]})
times = times.with_columns(minutes=pl.col("seconds") / 60)
times.rows()
1
[('r1', 15, 0.25), ('r2', 30, 0.5), ('r3', 90, 1.5)]
The durations are 0.25, 0.5 and 1.5 minutes, in the same order. Dividing by 60 also maps zero seconds to zero minutes.
Subtracting 0.5 from minutes gives the difference from the half-minute reference in minutes.
1
2
reference_minutes = 0.5
times.with_columns(from_reference_minutes=pl.col("minutes") - reference_minutes).rows()
1
[('r1', 15, 0.25, -0.25), ('r2', 30, 0.5, 0.0), ('r3', 90, 1.5, 1.0)]
The difference for r1 is -0.25 minutes, so it took 15 seconds less than the reference. For r2, the difference is zero because the duration was exactly 30 seconds. For r3, the difference is one minute.
To compare durations by their ratios, we can take logarithms and subtract the results. The natural logarithm of a positive number is the power to which the constant e, about 2.718, must be raised to produce that number. Polars log() takes this logarithm. The positive durations in minutes fall within its domain, the inputs for which it gives a finite real value.
Changing the origin changes the inputs to that transformation. Subtracting half a minute produces one negative difference and one zero in from_reference, both outside the domain. The expressions below compare logarithms of the original durations with logarithms of the shifted values. In guarded, pl.when() replaces the two nonpositive differences with null before log() runs.
1
2
3
4
5
6
7
from_reference = pl.col("minutes") - reference_minutes
times.select(
"response_id",
log_minutes=pl.col("minutes").log(),
log_from_reference=from_reference.log(),
guarded=pl.when(from_reference > 0).then(from_reference).log(),
)
1
2
3
4
5
6
7
8
9
10
shape: (3, 4)
┌─────────────┬─────────────┬────────────────────┬─────────┐
│ response_id ┆ log_minutes ┆ log_from_reference ┆ guarded │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪═════════════╪════════════════════╪═════════╡
│ r1 ┆ -1.386294 ┆ NaN ┆ null │
│ r2 ┆ -0.693147 ┆ -inf ┆ null │
│ r3 ┆ 0.405465 ┆ 0.0 ┆ 0.0 │
└─────────────┴─────────────┴────────────────────┴─────────┘
The first two log_minutes values are negative because 0.25 and 0.5 lie between 0 and 1. The log values are no longer durations in minutes. Subtracting the r1 log from the r2 log gives log(2) because 30 seconds is twice 15 seconds.
In log_from_reference, the inputs for those rows are -0.25 and 0, producing NaN and -inf. Both entries are null in guarded. For r3, 90 seconds is one minute above the reference, so guarded gives log(1), or 0.0.
All three original durations are valid measurements. The guarded calculation marks the two nonpositive differences as missing before applying the logarithm. For ratios of the original durations, the relevant calculation uses the logarithms of minutes. An analysis of positive differences from the reference asks a different question and requires its own choice of observations.