Different questions require different parts of the same survey table. Examining life satisfaction calls for a particular set of answer columns, while reviewing finished forms from Seoul or Busan requires a rule for choosing rows. Those choices must also account for missing information and preserve the association between each answer and its submission. We first select and rename columns, then express row-selection rules as logical conditions. With those foundations, we calculate new columns and order records for inspection, checking that the values still describe the same responses after each transformation.
7.1 Selecting and renaming columns
To examine the survey’s life-satisfaction answers, we can select the ten relevant columns from the full survey table. These columns are named SAT_1 through SAT_10. We include ResponseId and ID with them so that each row of answers can be traced to its submitted form and participant, including a participant who submitted twice.
With book as the working directory, readr::read_csv() reads data/practice/survey.csv as UTF-8. The col_types argument makes duration numeric and the other columns text. Empty fields become NA, and labels include any surrounding spaces.
dplyr::select() returns the named columns in the order listed. names() lists those columns, and dim() gives the row and column counts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| library(tidyverse)
survey <- read_csv(
"data/practice/survey.csv",
col_types = cols(`Duration (in seconds)` = col_double(), .default = col_character()),
na = "",
trim_ws = FALSE,
locale = locale(encoding = "UTF-8")
)
explicit <- select(
survey,
ResponseId, ID,
SAT_1, SAT_2, SAT_3, SAT_4, SAT_5, SAT_6, SAT_7, SAT_8, SAT_9, SAT_10
)
names(explicit)
dim(explicit)
|
1
2
3
4
| [1] "ResponseId" "ID" "SAT_1" "SAT_2" "SAT_3"
[6] "SAT_4" "SAT_5" "SAT_6" "SAT_7" "SAT_8"
[11] "SAT_9" "SAT_10"
[1] 503 12
|
The result contains all 503 response rows and the twelve requested columns.
All ten item names begin with SAT_. The helper starts_with("SAT_") can replace the full list. identical() tests whether both selections give exactly the same table.
1
2
3
| sat_view <- select(survey, ResponseId, ID, starts_with("SAT_"))
names(sat_view)
identical(explicit, sat_view)
|
1
2
3
4
| [1] "ResponseId" "ID" "SAT_1" "SAT_2" "SAT_3"
[6] "SAT_4" "SAT_5" "SAT_6" "SAT_7" "SAT_8"
[11] "SAT_9" "SAT_10"
[1] TRUE
|
The names match, and TRUE confirms that the prefix selected exactly the intended columns in this survey.
where(is.numeric) selects only the duration column. where(is.character) selects 31 columns because the identifiers and dates are text too. A shared name prefix distinguishes the ten satisfaction items here.
1
2
| names(select(survey, where(is.numeric)))
ncol(select(survey, where(is.character)))
|
1
2
| [1] "Duration (in seconds)"
[1] 31
|
With book as the working directory, pl.read_csv() reads the UTF-8 survey. With type inference off, the columns are text except for duration, which is declared as an integer. Unquoted empty fields become null, and the import does not trim spaces.
The DataFrame method select() returns the named columns in order. columns lists their names, and shape gives the row and column counts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| import polars as pl
survey = pl.read_csv(
"data/practice/survey.csv",
infer_schema=False,
schema_overrides={"Duration (in seconds)": pl.Int64},
empty_string_is_null=True,
encoding="utf8",
)
explicit = survey.select(
"ResponseId", "ID",
"SAT_1", "SAT_2", "SAT_3", "SAT_4", "SAT_5",
"SAT_6", "SAT_7", "SAT_8", "SAT_9", "SAT_10",
)
explicit.columns
explicit.shape
|
1
2
| ['ResponseId', 'ID', 'SAT_1', 'SAT_2', 'SAT_3', 'SAT_4', 'SAT_5', 'SAT_6', 'SAT_7', 'SAT_8', 'SAT_9', 'SAT_10']
(503, 12)
|
The twelve requested columns contain all 503 responses.
pl.col() also accepts a regular expression, a pattern for matching names. Polars treats ^SAT_.*$ as a pattern because ^ and $ mark the start and end of the name. The pattern matches the prefix SAT_, and .* matches zero or more characters after it. equals() tests whether this selects the same table as the explicit list.
1
2
3
| sat_view = survey.select("ResponseId", "ID", pl.col("^SAT_.*$"))
sat_view.columns
explicit.equals(sat_view)
|
1
2
| ['ResponseId', 'ID', 'SAT_1', 'SAT_2', 'SAT_3', 'SAT_4', 'SAT_5', 'SAT_6', 'SAT_7', 'SAT_8', 'SAT_9', 'SAT_10']
True
|
The displayed names are the two identifiers and SAT_1 through SAT_10. True confirms that the pattern selected the same table as the explicit names.
pl.col(pl.Int64) selects columns of that specific 64-bit integer type. Only duration has that type here. pl.col(pl.String) includes identifiers and dates along with satisfaction answers, so it cannot isolate the ten items.
1
2
| survey.select(pl.col(pl.Int64)).columns
len(survey.select(pl.col(pl.String)).columns)
|
1
2
| ['Duration (in seconds)']
31
|
Renaming a column
The full survey also records how long each form took. A shorter name for Duration (in seconds) makes time comparisons easier to read. Renaming should change that label without changing the values or the set of responses.
In dplyr::rename(), the new name goes to the left of = and the existing name goes to the right. The new table, survey_seconds, uses seconds for Duration (in seconds) in the full survey table. Response R_Z4kK41wEM10D gives one value to trace, and identical() tests whether any duration changed.
1
2
3
4
5
6
| survey_seconds <- rename(survey, seconds = `Duration (in seconds)`)
dim(survey_seconds)
is_response <- survey$ResponseId == "R_Z4kK41wEM10D"
survey$`Duration (in seconds)`[is_response]
survey_seconds$seconds[is_response]
identical(survey$`Duration (in seconds)`, survey_seconds$seconds)
|
1
2
3
4
| [1] 503 32
[1] 578
[1] 578
[1] TRUE
|
Both columns record 578 seconds for this response. The final TRUE confirms that all the durations match.
The Polars DataFrame method rename() takes a dictionary from old names to new names. Here it renames Duration (in seconds) in the full survey table. The duration for R_Z4kK41wEM10D appears under seconds in survey_seconds, and equals() checks the full column.
1
2
3
4
5
6
| survey_seconds = survey.rename({"Duration (in seconds)": "seconds"})
survey_seconds.shape
is_response = survey["ResponseId"] == "R_Z4kK41wEM10D"
survey["Duration (in seconds)"].filter(is_response)[0]
survey_seconds["seconds"].filter(is_response)[0]
survey["Duration (in seconds)"].equals(survey_seconds["seconds"])
|
1
2
3
4
| (503, 32)
578
578
True
|
The shape is (503, 32) as before, the inspected value is 578, and the full-column comparison is True. Only the duration’s name changed.
7.2 Selecting rows with explicit predicates
Which finished forms list Seoul or Busan as the participant’s region of residence? For this review, Finished must equal the text "TRUE" and Region must match one of the two city names. Each test is a predicate with one result per response. A finished form that lists Daegu falls outside this review because of its region alone.
survey$Finished == "TRUE" gives one logical value per response. %in% tests whether a region is in review_regions, and & combines the two results position by position. Rows 1, 3 and 180 are all finished, so their different outcomes depend only on the region test.
1
2
3
4
5
6
7
8
9
10
| review_regions <- c("Seoul", "Busan")
is_finished <- survey$Finished == "TRUE"
in_region <- survey$Region %in% review_regions
in_review <- is_finished & in_region
examples <- c(1, 3, 180)
survey$Finished[examples]
survey$Region[examples]
is_finished[examples]
in_region[examples]
in_review[examples]
|
1
2
3
4
5
| [1] "TRUE" "TRUE" "TRUE"
[1] "Seoul" "Daegu" NA
[1] TRUE TRUE TRUE
[1] TRUE FALSE FALSE
[1] TRUE FALSE FALSE
|
Here %in% gives TRUE for Seoul and FALSE for both Daegu and the missing region. Neither Daegu nor NA matches a name in review_regions.
dplyr::filter() selects rows where its condition is TRUE. In this comparison, Finished and Region refer to columns of survey, and review_regions comes from the session. Assigning the result to review_responses makes the subset available alongside the full survey.
1
2
3
4
5
| review_responses <- filter(survey, Finished == "TRUE" & Region %in% review_regions)
dim(review_responses)
unique(review_responses$Finished)
unique(review_responses$Region)
n_distinct(review_responses$ID)
|
1
2
3
4
| [1] 117 32
[1] "TRUE"
[1] "Seoul" "Busan"
[1] 116
|
The result has all 32 columns and 117 finished forms from Seoul or Busan. They came from 116 participants, so one person submitted two of the forms in this subset.
The constructed table has durations of 59 seconds, exactly 60 seconds and a missing value. For the missing duration, seconds < 60 is unknown. Can reversing that condition include the row?
1
2
3
4
5
6
7
8
| responses <- tibble(
response_id = c("r1", "r2", "r3"),
participant_id = c("p1", "p1", "p2"),
seconds = c(59, 60, NA)
)
mutate(responses, below_60 = seconds < 60)
filter(responses, seconds < 60)
filter(responses, !(seconds < 60))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # A tibble: 3 × 4
response_id participant_id seconds below_60
<chr> <chr> <dbl> <lgl>
1 r1 p1 59 TRUE
2 r2 p1 60 FALSE
3 r3 p2 NA NA
# A tibble: 1 × 3
response_id participant_id seconds
<chr> <chr> <dbl>
1 r1 p1 59
# A tibble: 1 × 3
response_id participant_id seconds
<chr> <chr> <dbl>
1 r2 p1 60
|
The first filter selects r1 at 59 seconds. Negating the time comparison selects r2 at exactly 60. For r3, both tests give NA, so neither filter selects that response. In a vector indexed with [, an NA in the logical index would return a missing element.
In Polars, pl.col("Finished") == "TRUE" tests completion, and pl.col("Region").is_in(review_regions) tests the region. & combines these expressions, which select() evaluates into named columns. A comparison needs parentheses when written beside &, because Python applies & before ==. The forms at positions 0, 2 and 179 are all finished, so only their regions can affect the decision.
1
2
3
4
5
6
7
8
9
10
11
12
13
| review_regions = ["Seoul", "Busan"]
is_finished = pl.col("Finished") == "TRUE"
in_region = pl.col("Region").is_in(review_regions)
decisions = survey.select(
"Finished",
"Region",
is_finished=is_finished,
in_region=in_region,
in_review=is_finished & in_region,
)
decisions.row(0)
decisions.row(2)
decisions.row(179)
|
1
2
3
| ('TRUE', 'Seoul', True, True, True)
('TRUE', 'Daegu', True, False, False)
('TRUE', None, True, None, None)
|
The last tuple is a finished form with no recorded region. Both in_region and in_review are null for that form.
survey.filter() selects a row when the combined expression is true. Assigning the result to review_responses gives the review its own table.
1
2
3
4
5
6
7
| review_responses = survey.filter(
(pl.col("Finished") == "TRUE") & pl.col("Region").is_in(review_regions)
)
review_responses.shape
review_responses["Finished"].unique(maintain_order=True).to_list()
review_responses["Region"].unique(maintain_order=True).to_list()
review_responses["ID"].n_unique()
|
1
2
3
4
| (117, 32)
['TRUE']
['Seoul', 'Busan']
116
|
The review contains all 32 columns. Its 117 finished forms come from 116 participants, so one participant submitted two of them.
The regional review requires both conditions. Replacing & with | accepts a response that satisfies either condition, while ~ negates a condition. Each height below counts responses selected by one of these alternative rules.
1
2
3
| survey.filter(is_finished | in_region).height
survey.filter(~is_finished).height
survey.filter(~in_region).height
|
In this survey, every response that lists Seoul or Busan is finished, so the first filter selects all 502 finished responses. The second selects the one unfinished form. The third selects 382 responses with another recorded region. A missing region still gives null when the test is negated.
These expressions use & and | to combine decisions for individual rows. Python’s and instead asks for a single truth value, which a Polars expression cannot provide.
1
2
| # Deliberate error: and asks an expression for one truth value
is_finished and in_region
|
1
| TypeError: the truth value of an Expr is ambiguous
|
A constructed table with durations of 59 seconds, exactly 60 seconds and a missing value shows how a numerical comparison handles an unknown input. None becomes null in Polars. The below_60 column records the decision for every row; filter() selects only rows whose decision is true.
1
2
3
4
5
6
7
8
9
| responses = pl.DataFrame(
{
"response_id": ["r1", "r2", "r3"],
"participant_id": ["p1", "p1", "p2"],
"seconds": [59, 60, None],
}
)
responses.with_columns(below_60=pl.col("seconds") < 60)
responses.filter(pl.col("seconds") < 60)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| shape: (3, 4)
┌─────────────┬────────────────┬─────────┬──────────┐
│ response_id ┆ participant_id ┆ seconds ┆ below_60 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ bool │
╞═════════════╪════════════════╪═════════╪══════════╡
│ r1 ┆ p1 ┆ 59 ┆ true │
│ r2 ┆ p1 ┆ 60 ┆ false │
│ r3 ┆ p2 ┆ null ┆ null │
└─────────────┴────────────────┴─────────┴──────────┘
shape: (1, 3)
┌─────────────┬────────────────┬─────────┐
│ response_id ┆ participant_id ┆ seconds │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 │
╞═════════════╪════════════════╪═════════╡
│ r1 ┆ p1 ┆ 59 │
└─────────────┴────────────────┴─────────┘
|
Only r1, at 59 seconds, appears in the filtered table. Reversing the condition would select r2, at 60 seconds. For r3, both the comparison and its negation are null because the duration is unknown.
Both languages select the same 117 finished forms for the regional review. On the full survey, ~in_region in Polars selects the 382 responses that name another region. In R, !in_region selects 386 because it also includes the four forms whose region is unknown.
7.3 Creating columns from existing values
The filter for times under a minute selects only r1 from the three constructed responses. How can the table also show why the other two were not selected? Alongside each duration in minutes, a short column can record true for 59 seconds, false for 60, and unknown for a missing duration.
mutate() adds columns to a new table. Here it calculates minutes from seconds in each row and does not change the identifiers or original duration.
1
| mutate(responses, minutes = seconds / 60)
|
1
2
3
4
5
6
| # A tibble: 3 × 4
response_id participant_id seconds minutes
<chr> <chr> <dbl> <dbl>
1 r1 p1 59 0.983
2 r2 p1 60 1
3 r3 p2 NA NA
|
The first duration is 59/60 of a minute, displayed as 0.983. The second is exactly 1 minute. For the missing duration, the result is NA.
For each response, dplyr::if_else() uses the result of seconds < 60 to choose the flag value. The second and third arguments give the values for a true and a false comparison. missing = NA specifies the flag for an unknown duration.
1
2
3
4
5
6
| timed <- mutate(
responses,
minutes = seconds / 60,
short = if_else(seconds < 60, TRUE, FALSE, missing = NA)
)
timed$short
|
1
2
| # Deliberate error: branches of different types
if_else(responses$seconds < 60, TRUE, "no")
|
1
2
| Error in `if_else()`:
! Can't combine `true` <logical> and `false` <character>.
|
The first call returns a logical flag. The second fails because its two alternatives, the logical value TRUE and the text "no", have no common type in if_else().
In timed, each source duration appears beside its value in minutes and its short flag. The identical() comparison checks that its three original columns are exactly the same as responses.
1
2
| timed
identical(select(timed, response_id, participant_id, seconds), responses)
|
1
2
3
4
5
6
7
| # A tibble: 3 × 5
response_id participant_id seconds minutes short
<chr> <chr> <dbl> <dbl> <lgl>
1 r1 p1 59 0.983 TRUE
2 r2 p1 60 1 FALSE
3 r3 p2 NA NA NA
[1] TRUE
|
At exactly 60 seconds, short is false. Both new columns are NA for the missing duration. The final TRUE confirms that the source columns did not change.
Subtracting 1 from minutes gives the difference in minutes from the cutoff. For r1, the difference is negative because 59 seconds is one second short of a minute. Here mutate() reads minutes from timed. Within a single mutate() call, later arguments can also use a column created by an earlier one.
1
| mutate(timed, minutes_from_one = minutes - 1)
|
1
2
3
4
5
6
| # A tibble: 3 × 6
response_id participant_id seconds minutes short minutes_from_one
<chr> <chr> <dbl> <dbl> <lgl> <dbl>
1 r1 p1 59 0.983 TRUE -0.0167
2 r2 p1 60 1 FALSE 0
3 r3 p2 NA NA NA NA
|
Polars with_columns() returns the source columns together with the new ones. Dividing pl.col("seconds") by 60 gives a value in minutes for each response.
1
| responses.with_columns(minutes=pl.col("seconds") / 60)
|
1
2
3
4
5
6
7
8
9
10
| shape: (3, 4)
┌─────────────┬────────────────┬─────────┬──────────┐
│ response_id ┆ participant_id ┆ seconds ┆ minutes │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 │
╞═════════════╪════════════════╪═════════╪══════════╡
│ r1 ┆ p1 ┆ 59 ┆ 0.983333 │
│ r2 ┆ p1 ┆ 60 ┆ 1.0 │
│ r3 ┆ p2 ┆ null ┆ null │
└─────────────┴────────────────┴─────────┴──────────┘
|
In the new f64 column, 59/60 of a minute is displayed as 0.983333, exactly one minute appears as 1.0, and the missing duration produces null.
In pl.when(condition).then(value).otherwise(value), a row receives the then value when its condition is true. With .otherwise(False), a missing duration receives the same flag as 60 seconds. Testing is_null() first allows the expression to return None for a missing duration.
1
2
3
4
5
6
7
8
9
10
| two_state = pl.when(pl.col("seconds") < 60).then(True).otherwise(False)
responses.with_columns(short=two_state)["short"].to_list()
short = (
pl.when(pl.col("seconds").is_null())
.then(None)
.when(pl.col("seconds") < 60)
.then(True)
.otherwise(False)
)
responses.with_columns(short=short)["short"].to_list()
|
1
2
| [True, False, False]
[True, False, None]
|
For r3, the last entry changes from False to None, distinguishing an unknown duration from a known duration of at least 60 seconds. The resulting column can represent Boolean values and nulls. Using True and pl.lit("no") as the two alternatives would instead produce strings.
The condition determines which result a row receives, but it does not protect an invalid branch from evaluation. Polars can evaluate branches independently of the condition, as the reference for when() explains. A branch that names a nonexistent column raises an error even if no row selects it.
In timed, minutes and short can be added in one with_columns() call because both depend only on seconds. equals() checks the original columns against responses.
1
2
3
| timed = responses.with_columns(minutes=pl.col("seconds") / 60, short=short)
timed
timed.select("response_id", "participant_id", "seconds").equals(responses)
|
1
2
3
4
5
6
7
8
9
10
11
| shape: (3, 5)
┌─────────────┬────────────────┬─────────┬──────────┬───────┐
│ response_id ┆ participant_id ┆ seconds ┆ minutes ┆ short │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 ┆ bool │
╞═════════════╪════════════════╪═════════╪══════════╪═══════╡
│ r1 ┆ p1 ┆ 59 ┆ 0.983333 ┆ true │
│ r2 ┆ p1 ┆ 60 ┆ 1.0 ┆ false │
│ r3 ┆ p2 ┆ null ┆ null ┆ null │
└─────────────┴────────────────┴─────────┴──────────┴───────┘
True
|
At exactly 60 seconds, short is false. For the response with no recorded time, both minutes and short are null. The final True confirms that the original columns match responses.
minutes_from_one gives the difference in minutes from the cutoff. A negative value for r1 means it took less than a minute. Each expression in with_columns() reads the table passed to that call. A second call on timed can therefore use minutes, which the first call created.
1
| timed.with_columns(minutes_from_one=pl.col("minutes") - 1)
|
1
2
3
4
5
6
7
8
9
10
| shape: (3, 6)
┌─────────────┬────────────────┬─────────┬──────────┬───────┬──────────────────┐
│ response_id ┆ participant_id ┆ seconds ┆ minutes ┆ short ┆ minutes_from_one │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 ┆ bool ┆ f64 │
╞═════════════╪════════════════╪═════════╪══════════╪═══════╪══════════════════╡
│ r1 ┆ p1 ┆ 59 ┆ 0.983333 ┆ true ┆ -0.016667 │
│ r2 ┆ p1 ┆ 60 ┆ 1.0 ┆ false ┆ 0.0 │
│ r3 ┆ p2 ┆ null ┆ null ┆ null ┆ null │
└─────────────┴────────────────┴─────────┴──────────┴───────┴──────────────────┘
|
7.4 Ordering rows and resolving ties
The full survey includes people who submitted twice. A completion flag describes each form, but comparing their order also requires the recorded end times. Which submission ended first for participants 0301, 0449, and 0489? Sorting by ID groups each pair of forms, and sorting by End Date within each pair identifies the earlier submission. Finished then shows whether that form was complete.
dplyr::arrange() sorts whole rows, first by ID and then by End Date within each ID. The end times are text in the fixed format YYYY-MM-DD HH:MM:SS, all in Korean local time. The year comes first, followed by smaller units in fixed-width fields, so text order is chronological here. Text order puts 10/1/2024 before 9/30/2024 because it compares the strings from the left, where 1 comes before 9.
1
2
3
4
5
6
| repeated_ids <- c("0301", "0449", "0489")
by_end <- arrange(survey, ID, `End Date`)
dim(by_end)
by_end |>
filter(ID %in% repeated_ids) |>
select(ID, `End Date`, ResponseId, Finished)
|
1
2
3
4
5
6
7
8
9
10
| [1] 503 32
# A tibble: 6 × 4
ID `End Date` ResponseId Finished
<chr> <chr> <chr> <chr>
1 0301 2024-04-02 16:48:04 R_WEanrtqrVeIp TRUE
2 0301 2024-04-02 16:48:51 R_LmcIXkg8nskK TRUE
3 0449 2024-04-17 14:26:18 R_EY0X7OFCR5OJ TRUE
4 0449 2024-04-22 16:27:19 R_D0utZ1mh1tHG TRUE
5 0489 2024-04-16 14:11:04 R_JbfYiyWlRfK2 FALSE
6 0489 2024-04-17 14:13:31 R_fer2gcP8qhbe TRUE
|
The result has all 503 rows. In the six displayed records, each participant’s responses are adjacent and ordered by end time. For 0489, the earlier response is marked unfinished, so the earliest response is not always a complete one.
desc() reverses a sort key, a column or expression that sets the order. Applied to End Date, it places each participant’s later response first without reversing the ascending order of participant IDs.
1
2
3
| arrange(survey, ID, desc(`End Date`)) |>
filter(ID %in% repeated_ids) |>
select(ID, `End Date`, ResponseId)
|
1
2
3
4
5
6
7
8
9
| # A tibble: 6 × 3
ID `End Date` ResponseId
<chr> <chr> <chr>
1 0301 2024-04-02 16:48:51 R_LmcIXkg8nskK
2 0301 2024-04-02 16:48:04 R_WEanrtqrVeIp
3 0449 2024-04-22 16:27:19 R_D0utZ1mh1tHG
4 0449 2024-04-17 14:26:18 R_EY0X7OFCR5OJ
5 0489 2024-04-17 14:13:31 R_fer2gcP8qhbe
6 0489 2024-04-16 14:11:04 R_JbfYiyWlRfK2
|
The two end times differ in each of the three survey pairs shown above. In a separate table, two responses share an end time and the third has none. For this tibble, arrange() puts missing times last, even with desc(). Sorting on !is.na(`End Date`) before the time itself puts the missing time first within each ID, since FALSE sorts before TRUE.
1
2
3
4
5
6
7
| submissions <- tibble(
ResponseId = c("r2", "r3", "r1"),
ID = c("0007", "0007", "0007"),
`End Date` = c("2024-04-02 16:48:04", NA, "2024-04-02 16:48:04")
)
arrange(submissions, ID, `End Date`)
arrange(submissions, ID, !is.na(`End Date`), `End Date`)
|
1
2
3
4
5
6
7
8
9
10
11
12
| # A tibble: 3 × 3
ResponseId ID `End Date`
<chr> <chr> <chr>
1 r2 0007 2024-04-02 16:48:04
2 r1 0007 2024-04-02 16:48:04
3 r3 0007 <NA>
# A tibble: 3 × 3
ResponseId ID `End Date`
<chr> <chr> <chr>
1 r3 0007 <NA>
2 r2 0007 2024-04-02 16:48:04
3 r1 0007 2024-04-02 16:48:04
|
The responses r2 and r1 tie because both their ID and their end time match. In both displays, arrange() puts these tied rows in their original order. Adding ResponseId as the last sort key gives them an order that does not depend on which came first in the input.
1
| arrange(submissions, ID, `End Date`, ResponseId)
|
1
2
3
4
5
6
| # A tibble: 3 × 3
ResponseId ID `End Date`
<chr> <chr> <chr>
1 r1 0007 2024-04-02 16:48:04
2 r2 0007 2024-04-02 16:48:04
3 r3 0007 <NA>
|
Both responses appear, with r1 first by identifier. Their identical end times give no evidence that r1 actually finished earlier.
Polars sort() orders whole rows by ID and then End Date. These end times all use Korean local time and the fixed format YYYY-MM-DD HH:MM:SS. With the year first and every field a fixed width, sorting the text puts the times in chronological order. Text order puts 10/1/2024 before 9/30/2024 because it compares the strings from the left, where 1 comes before 9. With Finished beside each time, the ordered responses also show whether the earlier submission was complete.
1
2
3
4
| repeated_ids = ["0301", "0449", "0489"]
by_end = survey.sort("ID", "End Date")
by_end.shape
by_end.filter(pl.col("ID").is_in(repeated_ids)).select("ID", "End Date", "ResponseId", "Finished")
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| (503, 32)
shape: (6, 4)
┌──────┬─────────────────────┬────────────────┬──────────┐
│ ID ┆ End Date ┆ ResponseId ┆ Finished │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞══════╪═════════════════════╪════════════════╪══════════╡
│ 0301 ┆ 2024-04-02 16:48:04 ┆ R_WEanrtqrVeIp ┆ TRUE │
│ 0301 ┆ 2024-04-02 16:48:51 ┆ R_LmcIXkg8nskK ┆ TRUE │
│ 0449 ┆ 2024-04-17 14:26:18 ┆ R_EY0X7OFCR5OJ ┆ TRUE │
│ 0449 ┆ 2024-04-22 16:27:19 ┆ R_D0utZ1mh1tHG ┆ TRUE │
│ 0489 ┆ 2024-04-16 14:11:04 ┆ R_JbfYiyWlRfK2 ┆ FALSE │
│ 0489 ┆ 2024-04-17 14:13:31 ┆ R_fer2gcP8qhbe ┆ TRUE │
└──────┴─────────────────────┴────────────────┴──────────┘
|
The sorted table has 503 rows and 32 columns. For 0489, the unfinished form ended on April 16 and the finished form on April 17. Both appear, with the unfinished form first.
The descending list gives one direction per sort key, a column that sets the order. [False, True] sorts IDs in ascending order and end times in descending order. With descending=True, the IDs would also sort in descending order.
1
2
3
4
5
| (
survey.sort("ID", "End Date", descending=[False, True])
.filter(pl.col("ID").is_in(repeated_ids))
.select("ID", "End Date", "ResponseId")
)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| shape: (6, 3)
┌──────┬─────────────────────┬────────────────┐
│ ID ┆ End Date ┆ ResponseId │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════╪═════════════════════╪════════════════╡
│ 0301 ┆ 2024-04-02 16:48:51 ┆ R_LmcIXkg8nskK │
│ 0301 ┆ 2024-04-02 16:48:04 ┆ R_WEanrtqrVeIp │
│ 0449 ┆ 2024-04-22 16:27:19 ┆ R_D0utZ1mh1tHG │
│ 0449 ┆ 2024-04-17 14:26:18 ┆ R_EY0X7OFCR5OJ │
│ 0489 ┆ 2024-04-17 14:13:31 ┆ R_fer2gcP8qhbe │
│ 0489 ┆ 2024-04-16 14:11:04 ┆ R_JbfYiyWlRfK2 │
└──────┴─────────────────────┴────────────────┘
|
The constructed submissions has two equal end times and one missing time. The Polars DataFrame method sort() puts nulls first by default. With nulls_last=True, the row with the missing end time comes last.
1
2
3
4
5
6
7
8
9
| submissions = pl.DataFrame(
{
"ResponseId": ["r2", "r3", "r1"],
"ID": ["0007", "0007", "0007"],
"End Date": ["2024-04-02 16:48:04", None, "2024-04-02 16:48:04"],
}
)
submissions.sort("ID", "End Date")
submissions.sort("ID", "End Date", nulls_last=True)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| shape: (3, 3)
┌────────────┬──────┬─────────────────────┐
│ ResponseId ┆ ID ┆ End Date │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞════════════╪══════╪═════════════════════╡
│ r3 ┆ 0007 ┆ null │
│ r2 ┆ 0007 ┆ 2024-04-02 16:48:04 │
│ r1 ┆ 0007 ┆ 2024-04-02 16:48:04 │
└────────────┴──────┴─────────────────────┘
shape: (3, 3)
┌────────────┬──────┬─────────────────────┐
│ ResponseId ┆ ID ┆ End Date │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞════════════╪══════╪═════════════════════╡
│ r2 ┆ 0007 ┆ 2024-04-02 16:48:04 │
│ r1 ┆ 0007 ┆ 2024-04-02 16:48:04 │
│ r3 ┆ 0007 ┆ null │
└────────────┴──────┴─────────────────────┘
|
The responses r2 and r1 have equal values for both sort keys, ID and End Date. They appear in input order here. To guarantee input order for ties, sort() requires maintain_order=True. A different rule uses the distinct ResponseId values as the final key.
1
| submissions.sort("ID", "End Date", "ResponseId", nulls_last=True)
|
1
2
3
4
5
6
7
8
9
10
| shape: (3, 3)
┌────────────┬──────┬─────────────────────┐
│ ResponseId ┆ ID ┆ End Date │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞════════════╪══════╪═════════════════════╡
│ r1 ┆ 0007 ┆ 2024-04-02 16:48:04 │
│ r2 ┆ 0007 ┆ 2024-04-02 16:48:04 │
│ r3 ┆ 0007 ┆ null │
└────────────┴──────┴─────────────────────┘
|
With the missing time last, the order is r1, r2, r3. The identifier puts r1 before r2. Their identical end times cannot tell you which submission actually finished first.
Sorting records and sorting values
After sorting, does each participant ID still belong to its own answers? Sorting by_end and survey by ResponseId lines up matching rows, so the two tables can be compared record by record. In id_sorted_alone, only the ID values move. Looking up the same response in each table shows which participant ID is attached to its answers.
1
2
3
4
| identical(arrange(by_end, ResponseId), arrange(survey, ResponseId))
id_sorted_alone <- mutate(survey, ID = sort(ID))
id_sorted_alone$ID[id_sorted_alone$ResponseId == "R_Z4kK41wEM10D"]
by_end$ID[by_end$ResponseId == "R_Z4kK41wEM10D"]
|
1
2
3
| [1] TRUE
[1] "0001"
[1] "0429"
|
1
2
3
4
| by_end.sort("ResponseId").equals(survey.sort("ResponseId"))
id_sorted_alone = survey.with_columns(pl.col("ID").sort())
id_sorted_alone["ID"].filter(id_sorted_alone["ResponseId"] == "R_Z4kK41wEM10D")[0]
by_end["ID"].filter(by_end["ResponseId"] == "R_Z4kK41wEM10D")[0]
|
After the two tables are sorted by ResponseId, the full-table comparison confirms that by_end contains the same records as survey. Response R_Z4kK41wEM10D still belongs to participant 0429. Sorting the ID column alone pairs its answers with the wrong participant, 0001.