Post

Reading a Rectangular File

Reading a survey file without an error does not establish that its values were interpreted correctly. An identifier such as 0429 can become the number 429, and treating a refusal code as missing can erase the distinction between refusal and a blank answer. To diagnose such changes, we need to understand how a file’s text becomes table values. This chapter follows that process for comma-separated values (CSV) files, from recognizing records and fields to specifying types, missing-value rules, and text encoding. We then compare the imported table with its source to determine whether an apparent problem arose during import.

6.1 Records, headers, delimiters, and quoting

Open data/practice/survey.csv in Positron’s editor. Its first line begins ResponseId,Start Date,End Date,ID,Gender and lists 32 column names in all. This line is the header. In this file, each later line is a record of one survey response, and each value in a record is a field. The constructed fragment below has two responses and three columns. Which commas separate fields in the first response?

response_id,participant_id,note
r1,p1,"talk, then rest"
r2,p1,walk

A delimiter marks the boundary between fields. In this fragment, the first two commas on the r1 line are delimiters. The third is inside the quoted note talk, then rest. Splitting at every comma produces the four pieces in Table 6.1, and the last has no column name. A quoted field can also contain a line break, so one CSV record can span several lines.

Table 6.1. Splitting the record for r1 at every comma.

PieceText of the pieceHeader name it would receive
1r1response_id
2p1participant_id
3"talknote
4` then rest”`none

readr::read_csv() recognizes a quoted field. Loading tidyverse makes read_csv() available. The single quotation marks around the R string allow the note’s double quotation marks to appear inside it. I() tells read_csv() to read the string itself as CSV text.

1
2
3
4
5
6
7
8
library(tidyverse)
fragment <- I('response_id,participant_id,note
r1,p1,"talk, then rest"
r2,p1,walk')
notes <- read_csv(fragment)
notes
names(notes)
notes$note[1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Rows: 2 Columns: 3
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (3): response_id, participant_id, note

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# A tibble: 2 × 3
  response_id participant_id note           
  <chr>       <chr>          <chr>          
1 r1          p1             talk, then rest
2 r2          p1             walk           
[1] "response_id"    "participant_id" "note"          
[1] "talk, then rest"

The import reports two rows and three columns. In the file, double quotes enclose the first note. In the tibble, its value is talk, then rest, including the comma.

With book as the working directory, read_csv() can use the survey’s relative path. In the Excel workbook data/raw/survey/survey_raw.xlsx, the row below the column names contains the question text. In the practice CSV, the first response follows the header immediately.

1
2
survey <- read_csv("data/practice/survey.csv")
survey
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
Rows: 503 Columns: 32
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (27): ResponseId, ID, Gender, Region, SAT_1, SAT_2, SAT_3, SAT_4, SAT_5...
dbl   (2): Birth Year, Duration (in seconds)
lgl   (1): Finished
dttm  (2): Start Date, End Date

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# A tibble: 503 × 32
   ResponseId  `Start Date`        `End Date`          ID    Gender `Birth Year`
   <chr>       <dttm>              <dttm>              <chr> <chr>         <dbl>
 1 R_Z4kK41wE… 2024-04-01 08:43:31 2024-04-01 08:53:09 0429  Female         1965
 2 R_wPZVgoeW… 2024-04-01 09:28:51 2024-04-01 09:38:09 0050  Male           1983
 3 R_uqGhH8sz… 2024-04-01 09:43:31 2024-04-01 09:54:41 0400  Male           1970
 4 R_93JfYkur… 2024-04-01 10:29:42 2024-04-01 10:35:44 0147  Female         1993
 5 R_hopQ1ccn… 2024-04-01 10:47:15 2024-04-01 10:55:16 0394  Male           1998
 6 R_tWe6HhZK… 2024-04-01 10:50:48 2024-04-01 11:00:06 0076  Male           1993
 7 R_orU3Bd6O… 2024-04-01 10:58:23 2024-04-01 11:11:31 0355  Female         1999
 8 R_M9X7Sbo4… 2024-04-01 12:18:38 2024-04-01 12:26:04 0361  Female         1979
 9 R_SMvTd8Gc… 2024-04-01 12:32:07 2024-04-01 12:39:30 0139  Female         1998
10 R_pCzfgWQo… 2024-04-01 13:12:45 2024-04-01 13:21:22 0242  Female         1973
# ℹ 493 more rows
# ℹ 26 more variables: Region <chr>, SAT_1 <chr>, SAT_2 <chr>, SAT_3 <chr>,
#   SAT_4 <chr>, SAT_5 <chr>, SAT_6 <chr>, SAT_7 <chr>, SAT_8 <chr>,
#   SAT_9 <chr>, SAT_10 <chr>, STR_1 <chr>, STR_2 <chr>, STR_3 <chr>,
#   STR_4 <chr>, STR_5 <chr>, STR_6 <chr>, STR_7 <chr>, STR_8 <chr>,
#   STR_9 <chr>, STR_10 <chr>, ATTN_1 <chr>, Q_MULTI <chr>, Q_OPEN <chr>,
#   `Duration (in seconds)` <dbl>, Finished <lgl>
# ℹ Use `print(n = ...)` to see more rows

The tibble has 503 rows and 32 columns. The Console shows ten responses and the columns that fit its width. Even the first ResponseId is shortened to R_Z4kK41wE… on screen. Its full value in the file is R_Z4kK41wEM10D. The footer accounts for the other 493 rows and 26 columns.

In Python, three double quotation marks enclose a string that spans several lines and contains ordinary quotation marks. io.StringIO() wraps that string in an object that can be read like a file, and pl.read_csv() reads its CSV fields. The column names and the first note show how it handled the comma in the quoted text.

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

import polars as pl

fragment = """response_id,participant_id,note
r1,p1,"talk, then rest"
r2,p1,walk
"""
notes = pl.read_csv(io.StringIO(fragment))
notes
notes.columns
notes["note"][0]
1
2
3
4
5
6
7
8
9
10
11
shape: (2, 3)
┌─────────────┬────────────────┬─────────────────┐
│ response_id ┆ participant_id ┆ note            │
│ ---         ┆ ---            ┆ ---             │
│ str         ┆ str            ┆ str             │
╞═════════════╪════════════════╪═════════════════╡
│ r1          ┆ p1             ┆ talk, then rest │
│ r2          ┆ p1             ┆ walk            │
└─────────────┴────────────────┴─────────────────┘
['response_id', 'participant_id', 'note']
'talk, then rest'

The result has two rows and three columns. The first note is the string 'talk, then rest'. Its comma is part of the value. The surrounding single quotes are how Python displays a string.

pl.read_csv() finds the survey by its path relative to the working directory book. head(3) selects the first three rows for inspection, while shape reports the dimensions of the full DataFrame.

1
2
3
survey = pl.read_csv("data/practice/survey.csv")
survey.head(3)
survey.shape
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
shape: (3, 32)
┌─────────────┬─────────────┬─────────────┬─────┬───┬─────────┬────────────┬────────────┬──────────┐
│ ResponseId  ┆ Start Date  ┆ End Date    ┆ ID  ┆ … ┆ Q_MULTI ┆ Q_OPEN     ┆ Duration   ┆ Finished │
│ ---         ┆ ---         ┆ ---         ┆ --- ┆   ┆ ---     ┆ ---        ┆ (in        ┆ ---      │
│ str         ┆ str         ┆ str         ┆ i64 ┆   ┆ str     ┆ str        ┆ seconds)   ┆ bool     │
│             ┆             ┆             ┆     ┆   ┆         ┆            ┆ ---        ┆          │
│             ┆             ┆             ┆     ┆   ┆         ┆            ┆ i64        ┆          │
╞═════════════╪═════════════╪═════════════╪═════╪═══╪═════════╪════════════╪════════════╪══════════╡
│ R_Z4kK41wEM ┆ 2024-04-01  ┆ 2024-04-01  ┆ 429 ┆ … ┆ 1;2;3;6 ┆ null       ┆ 578        ┆ true     │
│ 10D         ┆ 08:43:31    ┆ 08:53:09    ┆     ┆   ┆         ┆            ┆            ┆          │
│ R_wPZVgoeWr ┆ 2024-04-01  ┆ 2024-04-01  ┆ 50  ┆ … ┆ 2;3;5;6 ┆ Went to    ┆ 558        ┆ true     │
│ WJ0         ┆ 09:28:51    ┆ 09:38:09    ┆     ┆   ┆         ┆ bed early. ┆            ┆          │
│ R_uqGhH8szq ┆ 2024-04-01  ┆ 2024-04-01  ┆ 400 ┆ … ┆ 2;3;4   ┆ null       ┆ 670        ┆ true     │
│ Jbo         ┆ 09:43:31    ┆ 09:54:41    ┆     ┆   ┆         ┆            ┆            ┆          │
└─────────────┴─────────────┴─────────────┴─────┴───┴─────────┴────────────┴────────────┴──────────┘
(503, 32)

The practice CSV has one header and no question-text row. The (3, 32) above the preview describes the three responses returned by head(3). The final (503, 32) describes the full table. Long values wrap on screen, and … marks columns omitted from the display.

Both imports have 503 rows and 32 columns. In the first response, readr reads the ID field 0429 as text. Polars infers an integer and displays 429. The row and column counts alone cannot reveal the missing zero.

6.2 Specifying types and preserving identifiers

On line 421 of data/practice/survey.csv, response R_D7sLfnz61bpc has participant ID 0007 and a duration of 895 seconds. The ID is a label used to match records. Reading it as the number 7 would discard the leading zeros. Parsing the duration converts the text 895 to a number we can divide by 60 to get minutes.

A CSV file does not declare column types. By default, readr::read_csv() infers them from up to 1,000 rows distributed through the file, while pl.read_csv() examines up to the first 100 rows. Table 6.2 shows what each reader infers for two constructed records, 0007,30 and 0012,90. A sample can miss an unusual value. Declaring the identifier as text means its spelling does not depend on which rows were sampled.

Table 6.2. How type inference and an explicit text type affect the participant ID 0007.

Reader and settingparticipant_id typeFirst participant_idseconds type
readr, inferredcharacter0007double
readr, declared as charactercharacter0007double
Polars, inferredi647i64
Polars, declared as StringString0007i64

In readr::read_csv(), col_types takes a specification built with cols(). Here col_character() reads both identifiers as text, and col_double() reads duration as a number. Backticks enclose Duration (in seconds) because its name contains spaces and parentheses. .default = col_character() reads the remaining columns as text. With all types specified, readr omits its type-guessing message. The first glimpse() shows the three selected columns of the imported survey. The region-code lookup uses text for all four columns, including the codes 01 and 01001.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
survey <- read_csv(
  "data/practice/survey.csv",
  col_types = cols(
    ResponseId = col_character(),
    ID = col_character(),
    `Duration (in seconds)` = col_double(),
    .default = col_character()
  )
)
glimpse(select(survey, ResponseId, ID, `Duration (in seconds)`))
codes <- read_csv(
  "data/practice/region_codes.csv",
  col_types = cols(.default = col_character())
)
glimpse(codes)
1
2
3
4
5
6
7
8
9
10
11
Rows: 503
Columns: 3
$ ResponseId              <chr> "R_Z4kK41wEM10D", "R_wPZVgoeWrWJ0", "R_uqGhH8s…
$ ID                      <chr> "0429", "0050", "0400", "0147", "0394", "0076"…
$ `Duration (in seconds)` <dbl> 578, 558, 670, 362, 481, 558, 788, 446, 443, 5…
Rows: 229
Columns: 4
$ `Province code` <chr> "01", "01", "01", "01", "01", "01", "01", "01", "01", …
$ `Province name` <chr> "Seoul", "Seoul", "Seoul", "Seoul", "Seoul", "Seoul", …
$ `District code` <chr> "01001", "01002", "01003", "01004", "01005", "01006", …
$ `District name` <chr> "Jongno-gu", "Jung-gu", "Yongsan-gu", "Seongdong-gu", …

The comparison survey$ResponseId == "R_D7sLfnz61bpc" marks the response on source line 421. Inside brackets, that same test retrieves its participant ID and its duration. typeof() checks the duration column’s type.

1
2
3
survey$ID[survey$ResponseId == "R_D7sLfnz61bpc"]
survey$`Duration (in seconds)`[survey$ResponseId == "R_D7sLfnz61bpc"]
typeof(survey$`Duration (in seconds)`)
1
2
3
[1] "0007"
[1] 895
[1] "double"

The ID matches the four characters in 0007, and typeof() confirms that the duration of 895 seconds is numeric.

Declaring a type also determines what happens when a field cannot be read that way. In a constructed example, col_double() asks read_csv() to read the scores 1 and refused as numbers. In the source string, \n represents a line break. problems(scores) reports any fields that could not be parsed.

1
2
3
4
5
6
scores <- read_csv(
  I("response_id,score\nr1,1\nr2,refused"),
  col_types = cols(response_id = col_character(), score = col_double())
)
scores
select(problems(scores), row, col, expected, actual)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Warning message:
One or more parsing issues, call `problems()` on your data frame for details,
e.g.:
  dat <- vroom(...)
  problems(dat) 
# A tibble: 2 × 2
  response_id score
  <chr>       <dbl>
1 r1              1
2 r2             NA
# A tibble: 1 × 4
    row   col expected actual 
  <int> <int> <chr>    <chr>  
1     3     2 a double refused

read_csv() warns and stores NA for refused. If you saw only that NA, you could mistake the response for a blank. In problems(scores), row 3 and column 2 locate the field. The row count includes the header. expected gives its requested type and actual shows the word refused.

With infer_schema=False, pl.read_csv() reads columns as String unless the schema_overrides dictionary specifies another type. Reading ID as text gives 0429 for the first participant. pl.Int64 suits the duration recorded in whole seconds. Codes such as 01 and 01001 begin with zero, so the region-code lookup is read as text.

1
2
3
4
5
6
7
8
9
10
11
12
13
survey = pl.read_csv(
    "data/practice/survey.csv",
    infer_schema=False,
    schema_overrides={
        "ResponseId": pl.String,
        "ID": pl.String,
        "Duration (in seconds)": pl.Int64,
    },
)
survey.select("ResponseId", "ID", "Duration (in seconds)").head(3)
codes = pl.read_csv("data/practice/region_codes.csv", infer_schema=False)
codes.schema
codes.head(3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
shape: (3, 3)
┌────────────────┬──────┬───────────────────────┐
│ ResponseId     ┆ ID   ┆ Duration (in seconds) │
│ ---            ┆ ---  ┆ ---                   │
│ str            ┆ str  ┆ i64                   │
╞════════════════╪══════╪═══════════════════════╡
│ R_Z4kK41wEM10D ┆ 0429 ┆ 578                   │
│ R_wPZVgoeWrWJ0 ┆ 0050 ┆ 558                   │
│ R_uqGhH8szqJbo ┆ 0400 ┆ 670                   │
└────────────────┴──────┴───────────────────────┘
Schema({'Province code': String, 'Province name': String, 'District code': String, 'District name': String})
shape: (3, 4)
┌───────────────┬───────────────┬───────────────┬───────────────┐
│ Province code ┆ Province name ┆ District code ┆ District name │
│ ---           ┆ ---           ┆ ---           ┆ ---           │
│ str           ┆ str           ┆ str           ┆ str           │
╞═══════════════╪═══════════════╪═══════════════╪═══════════════╡
│ 01            ┆ Seoul         ┆ 01001         ┆ Jongno-gu     │
│ 01            ┆ Seoul         ┆ 01002         ┆ Jung-gu       │
│ 01            ┆ Seoul         ┆ 01003         ┆ Yongsan-gu    │
└───────────────┴───────────────┴───────────────┴───────────────┘

survey["ResponseId"] == "R_D7sLfnz61bpc" gives a Boolean Series, is_0007_response. The Series method filter() selects values where that test is True. Applying it to both columns retrieves the participant ID and duration for the response on line 421.

1
2
3
is_0007_response = survey["ResponseId"] == "R_D7sLfnz61bpc"
survey["ID"].filter(is_0007_response)
survey["Duration (in seconds)"].filter(is_0007_response)
1
2
3
4
5
6
7
8
9
10
shape: (1,)
Series: 'ID' [str]
[
	"0007"
]
shape: (1,)
Series: 'Duration (in seconds)' [i64]
[
	895
]

The str Series contains "0007", and the i64 Series contains 895 seconds. The import reproduces the identifier’s spelling and reads the duration as an integer.

Declaring a type also determines what happens when a field cannot be read that way. In a constructed example, the score column contains 1 and refused. Declaring score as pl.Int64 asks Polars to read both as integers. Under the default settings, the first field it cannot parse stops the import. In the source string, \n represents a line break.

1
2
3
4
5
# Deliberate error: a value that does not fit a declared Int64 column
pl.read_csv(
    io.StringIO("response_id,score\nr1,1\nr2,refused\n"),
    schema_overrides={"score": pl.Int64},
)
1
polars.exceptions.ComputeError: could not parse `refused` as dtype `i64` at column 'score' (column number 2)

The error names the column score, the requested type i64, and the word refused. With ignore_errors=True, pl.read_csv() would finish this import and store a null for r2’s score. That null alone would give no indication that r2 recorded a refusal.

The duration of 895 seconds fits the declared numeric type. A negative number would fit it too, even though a survey cannot take less than zero seconds.

6.3 Missing fields, whitespace, and encoding

The three notes below look blank, but their source text differs. r1 has nothing after its comma, r2 has an empty quoted field, and r3 has two spaces inside quotation marks. Which differences survive the import?

response_id,note
r1,
r2,""
r3,"  "

In readr::read_csv(), na lists the field values to read as missing. Its default is c("", "NA"). With na = "", an empty field is missing and the literal letters NA are text in this character column. The default trim_ws = TRUE trims surrounding spaces. Here trim_ws = FALSE lets us see whether the two spaces in r3 are present. is.na() tests each note for missingness, and nchar() counts its characters.

1
2
3
4
5
6
7
blank_notes <- read_csv(
  I('response_id,note\nr1,\nr2,""\nr3,"  "'),
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
mutate(blank_notes, missing = is.na(note), characters = nchar(note))
1
2
3
4
5
6
# A tibble: 3 × 4
  response_id note  missing characters
  <chr>       <chr> <lgl>        <int>
1 r1          <NA>  TRUE            NA
2 r2          <NA>  TRUE            NA
3 r3          "  "  FALSE            2

The notes for r1 and r2 are both NA, so the imported notes cannot tell us which empty field was quoted. The note for r3 has two characters. With trimming still off, na = character() lists no missing values and both empty fields become empty strings. With the default missing values and trimming, all three notes become NA.

Some labels in the survey have surrounding spaces. To inspect those recorded differences, read_csv() reads label text without trimming and treats empty fields as missing. Only duration is read as numeric.

Reading the text also requires an encoding, the rule that determines how bytes represent characters. A byte can represent one of 256 values, conventionally numbered from 0 to 255. The supplied practice CSV files use UTF-8, and locale(encoding = "UTF-8") tells read_csv() to decode their bytes accordingly.

After import, unique() lists distinct values in order of first appearance. This lets us inspect label variants and missing-value codes without listing every response. The first three open answers provide a separate check on blank text fields.

1
2
3
4
5
6
7
8
9
10
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")
)
unique(survey$Gender)
head(survey$Q_OPEN, 3)
unique(survey$SAT_1)
1
2
3
4
5
6
 [1] "Female"  "Male"    "F"       "male"    "female"  "M"       " Female"
 [8] NA        "Other"   "Male "  
[1] NA                   "Went to bed early." NA                  
[1] "Strongly disagree" "Strongly agree"    "Neutral"          
[4] "Agree"             "Disagree"          NA                 
[7] "-99"              

With trim_ws = FALSE, " Female" and "Male " appear separately from "Female" and "Male". In the first life-satisfaction item, SAT_1, NA marks a blank answer and "-99" records a refusal. Adding "-99" to na would make those two cases indistinguishable in the imported column.

In pl.read_csv(), an unquoted empty field becomes null by default, and empty_string_is_null=True states that choice explicitly. With no null_values specified, no additional text is marked as missing. to_list() shows each note as a Python value. is_null() identifies missing notes, and str.len_chars(), one of the text functions grouped under .str, gives the length of each string.

1
2
3
4
5
6
7
8
9
10
blank_notes = pl.read_csv(
    io.StringIO('response_id,note\nr1,\nr2,""\nr3,"  "\n'),
    infer_schema=False,
    empty_string_is_null=True,
)
blank_notes["note"].to_list()
blank_notes.with_columns(
    missing=pl.col("note").is_null(),
    characters=pl.col("note").str.len_chars(),
)
1
2
3
4
5
6
7
8
9
10
11
[None, '', '  ']
shape: (3, 4)
┌─────────────┬──────┬─────────┬────────────┐
│ response_id ┆ note ┆ missing ┆ characters │
│ ---         ┆ ---  ┆ ---     ┆ ---        │
│ str         ┆ str  ┆ bool    ┆ u32        │
╞═════════════╪══════╪═════════╪════════════╡
│ r1          ┆ null ┆ true    ┆ null       │
│ r2          ┆      ┆ false   ┆ 0          │
│ r3          ┆      ┆ false   ┆ 2          │
└─────────────┴──────┴─────────┴────────────┘

Only the note for r1 is null. The cells for r2 and r3 both look blank, but their character counts are 0 and 2. Setting empty_string_is_null=False would turn the unquoted empty field into an empty string too.

Applying these choices to the survey, pl.read_csv() reads duration as an integer and the other fields as text. Unquoted empty fields become null, while labels with spaces and codes such as "-99" are read as recorded text.

Reading the text also requires an encoding, the rule that determines how bytes represent characters. A byte can represent one of 256 values, conventionally numbered from 0 to 255. The supplied file uses UTF-8, which encoding="utf8" selects explicitly.

After import, unique(maintain_order=True) lists distinct values in order of first appearance. This lets us inspect label variants and missing-value codes without listing every response. The first three open answers provide a separate check on blank text fields.

1
2
3
4
5
6
7
8
9
10
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",
)
survey["Gender"].unique(maintain_order=True)
survey["Q_OPEN"].head(3)
survey["SAT_1"].unique(maintain_order=True)
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
shape: (10,)
Series: 'Gender' [str]
[
	"Female"
	"Male"
	"F"
	"male"
	"female"
	"M"
	" Female"
	null
	"Other"
	"Male "
]
shape: (3,)
Series: 'Q_OPEN' [str]
[
	null
	"Went to bed early."
	null
]
shape: (7,)
Series: 'SAT_1' [str]
[
	"Strongly disagree"
	"Strongly agree"
	"Neutral"
	"Agree"
	"Disagree"
	null
	"-99"
]

Gender lists the recorded spellings, including " Female" and "Male ". Two of the first three responses have a blank Q_OPEN field. In the first life-satisfaction item, SAT_1, null marks a blank and "-99" records a refusal. Neither distinct-value list counts responses.

Encoding

The open answer for response R_oA7M9tOjykZC looks like Made a to-do list. in an editor. Would it match those words typed with ordinary spaces? We can identify the imported characters more precisely than their appearance allows. Unicode assigns each character a number called its code point, and UTF-8 represents that code point with one to four bytes.

The displays below show both characters and bytes. Byte values are commonly written in hexadecimal, or base 16, using digits 0 to 9 and letters a to f. For example, decimal 32 is 20 in hexadecimal.

The survey was read with locale(encoding = "UTF-8"). For this answer, utf8ToInt() gives the code point of each character, and charToRaw() gives the bytes of the imported string.

1
2
3
4
open_text <- survey$Q_OPEN[survey$ResponseId == "R_oA7M9tOjykZC"]
open_text
utf8ToInt(open_text)
charToRaw(open_text)
1
2
3
[1] "Made a to-do list."
 [1]  77  97 100 101 160  97  32 116 111  45 100 111  32 108 105 115 116  46
 [1] 4d 61 64 65 c2 a0 61 20 74 6f 2d 64 6f 20 6c 69 73 74 2e

The fifth code point is 160, written U+00A0 in hexadecimal. It is a no-break space, so the answer differs from the version typed with ordinary spaces. The later spaces have code point 32. UTF-8 uses the bytes c2 a0 for the no-break space and 20 for each ordinary space.

pl.read_csv() read the survey with encoding="utf8". ord() returns the Unicode code point for each of the first six characters in this answer. The first seven bytes of open_text.encode("utf-8") show how those characters are encoded.

1
2
3
4
open_text = survey["Q_OPEN"].filter(survey["ResponseId"] == "R_oA7M9tOjykZC")[0]
open_text
[ord(character) for character in open_text[:6]]
open_text.encode("utf-8")[:7]
1
2
3
'Made\xa0a to-do list.'
[77, 97, 100, 101, 160, 97]
b'Made\xc2\xa0a'

In Python’s display, \xa0 after Made represents one no-break space, code point 160. That is why the answer differs from the text typed with ordinary spaces. The bytes \xc2\xa0 come from encoding the imported string as UTF-8. This call does not read bytes directly from the CSV file.

A decoding error is different from the recorded difference between two space characters. If the UTF-8 bytes c2 a0 are read as Windows-1252, they are interpreted separately: c2 becomes Â, and a0 becomes a no-break space. Choosing the source file’s encoding is therefore part of reproducing its text, before deciding whether two recorded spellings should be treated alike.

6.4 Checking an imported table against its source

Do the imported row count and column names match survey.csv? This file has no quoted line breaks, so each line below the header is one response record. Even if the counts match, they cannot tell us whether the reader introduced a leading space or an unusual birth year. Comparing those two fields by response ID tests whether the import changed either value. A match for both tells us nothing about the accuracy of an answer we did not inspect.

read_lines() returns the source lines as a character vector. This header has no quoted fields, so strsplit() can separate its column names at the commas. The result is a list with one vector per string. [[1]] extracts the header’s vector, and identical() tests whether it matches names(survey). n_distinct() counts each identifier once, while summing is.na() counts missing identifiers, because each TRUE counts as 1.

1
2
3
4
5
6
7
8
source_lines <- read_lines("data/practice/survey.csv")
length(source_lines)
identical(names(survey), strsplit(source_lines[1], ",")[[1]])
dim(survey)
n_distinct(survey$ResponseId)
n_distinct(survey$ID)
sum(is.na(survey$ResponseId))
sum(is.na(survey$ID))
1
2
3
4
5
6
7
[1] 504
[1] TRUE
[1] 503  32
[1] 503
[1] 500
[1] 0
[1] 0

One of the 504 source lines is the header. The other 503 are responses, matching the 503 imported rows. All 32 column names match the header in order. The table has 503 distinct response IDs and no missing IDs. There are 500 distinct participant IDs, so some participants submitted more than once.

Did the import introduce the space in " Female" or the birth year "1890"? substr() shows the first 72 characters of source lines 52 and 84. The response IDs locate the matching imported fields.

1
2
3
substr(source_lines[c(52, 84)], 1, 72)
survey$Gender[survey$ResponseId == "R_q1lADNAzlNN2"]
survey$`Birth Year`[survey$ResponseId == "R_lkAt7hRguT1E"]
1
2
3
4
[1] "R_q1lADNAzlNN2,2024-04-03 10:36:15,2024-04-03 10:42:17,0511, Female,1977"
[2] "R_lkAt7hRguT1E,2024-04-04 15:50:54,2024-04-04 16:02:04,0222,Male,1890,Da"
[1] " Female"
[1] "1890"

Line 52 contains the leading space in " Female", and line 84 records "1890". Both imported fields match their source. The documented birth-year range for this synthetic survey is from 1965 to 2005, so 1890 falls outside it even though the import read it correctly.

Path.read_text(encoding="utf-8") reads the source text and splitlines() separates it into lines. The header has no quoted fields, so splitting it at commas gives the names to compare with survey.columns. The Series methods n_unique() and null_count() count distinct and missing identifiers.

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

source_lines = Path("data/practice/survey.csv").read_text(encoding="utf-8").splitlines()
len(source_lines)
survey.columns == source_lines[0].split(",")
survey.shape
survey["ResponseId"].n_unique()
survey["ID"].n_unique()
survey["ResponseId"].null_count()
survey["ID"].null_count()
1
2
3
4
5
6
7
504
True
(503, 32)
503
500
0
0

The 504 source lines include the header, so they account for 503 response rows. The 32 imported column names match the header in order. Each response has a distinct ResponseId, and none is missing. The 503 submissions came from 500 participants.

Did the leading space in the gender label and the birth year 1890 come from the file? Source lines 52 and 84 occupy Python positions 51 and 83. The comprehension shows their first 72 characters for comparison with the imported fields.

1
2
3
[line[:72] for line in (source_lines[51], source_lines[83])]
survey["Gender"].filter(survey["ResponseId"] == "R_q1lADNAzlNN2")[0]
survey["Birth Year"].filter(survey["ResponseId"] == "R_lkAt7hRguT1E")[0]
1
2
3
['R_q1lADNAzlNN2,2024-04-03 10:36:15,2024-04-03 10:42:17,0511, Female,1977', 'R_lkAt7hRguT1E,2024-04-04 15:50:54,2024-04-04 16:02:04,0222,Male,1890,Da']
' Female'
'1890'

The label on source line 52 has the same leading space as the imported value. On line 84, the file itself records 1890. That year falls outside the synthetic survey’s documented birth-year range, from 1965 to 2005.

Diagnosing an import from its source

The survey checks found unusual values that were already in the file. A disagreement in column structure instead directs us to how the reader interpreted the source. In the constructed example below, a title precedes the column names. The comma in Survey export, 2024 gives that title two fields, while the header and each response have three. What happens if the reader treats the title as the header?

Survey export, 2024
response_id,participant_id,SAT_1
r1,0007,Agree
r2,0012,-99
r3,0019,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
constructed <- I("Survey export, 2024
response_id,participant_id,SAT_1
r1,0007,Agree
r2,0012,-99
r3,0019,")
shifted <- read_csv(constructed, col_types = cols(.default = col_character()))
names(shifted)
repaired <- read_csv(
  constructed,
  skip = 1,
  col_types = cols(.default = col_character()),
  na = "",
  trim_ws = FALSE
)
names(repaired)
1
2
3
4
5
6
7
Warning message:
One or more parsing issues, call `problems()` on your data frame for details,
e.g.:
  dat <- vroom(...)
  problems(dat) 
[1] "Survey export" "2024"         
[1] "response_id"    "participant_id" "SAT_1"         

By default, readr::read_csv() uses Survey export and 2024 as the names and warns when it finds three fields in the next line. With skip = 1, it skips the title and reads the column names from the second line.

1
2
3
4
5
6
constructed = """Survey export, 2024
response_id,participant_id,SAT_1
r1,0007,Agree
r2,0012,-99
r3,0019,
"""
1
2
# Deliberate error: the title line read as the header
pl.read_csv(io.StringIO(constructed), infer_schema=False)
1
polars.exceptions.ComputeError: found more fields than defined in 'Schema'
1
2
repaired = pl.read_csv(io.StringIO(constructed), skip_rows=1, infer_schema=False)
repaired.columns
1
['response_id', 'participant_id', 'SAT_1']

pl.read_csv() expects two fields when it reads the title as the header. It stops when it finds three. With skip_rows=1, it reads response_id, participant_id, and SAT_1 from the second line as the column names.

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