How do I read selected columns with the right types using fread?
Read only the columns you need with fread’s select, and keep security codes as text with colClasses, so their leading zeros survive.
After this lesson, you can read only the columns you need from a large file and keep security codes as text, with their leading zeros.
What goes wrong when fread guesses the classes?
fread(path) from the data.table package guesses each column’s class from its values, so a security code written with only digits, such as AAA’s 012345678, becomes the integer 12345678 and loses its leading zero. A code that no longer has nine digits matches nothing when the table is joined to another by code.
The made-up file holds 200,000 trades of AAA, CCC and DDD on the 22 weekdays of April 2024, with a date, a ticker, a nine-digit code, a price in dollars per share and a size in shares. sapply(table, function(column) class(column)[1]) lists each column’s class.
date ticker code price size
"IDate" "character" "integer" "numeric" "integer"
print(unique(guessed$code))
[1] 987654320 12345678 23456789
How do I read selected columns with the right classes?
select = c("date", "code", "size") reads only the named columns, and colClasses = list(character = "code") reads the code as text, so all three codes keep their nine digits. Reading fewer columns saves time and memory on a large file.
stopifnot() stops the code if the code column is not text or a code does not have nine characters, so a later change to the file cannot pass unnoticed. nchar() counts characters.
The following box reads three columns with the code as text and checks the codes.
Read only the code and size columns, with the code as text, and print the shares traded per code. You should see three codes with their leading digits intact.
TipShow answer
by = code sums the shares per code, as in the lesson on data.table.