How do I combine many daily files into one table in R?
Read a folder of daily files with lapply and fread, stack them with rbindlist, keep the source of every row with idcol, and see why growing a table with rbind in a loop is slow.
After this lesson, you can read a folder of daily trade files into one table that remembers each row’s file.
How do I read every file into one table?
lapply(paths, fread) reads each daily file into a list of tables, and rbindlist(tables, use.names = TRUE, idcol = "file") stacks them into one table with a column naming each row’s file, so the three made-up files of 1,000 trades each become 3,000 rows. The date in each file name, read with substr(file, 8, 17), becomes a date column.
The files hold made-up trades of AAA and BBB on 1 to 3 April 2024, with a price in dollars per share and a size in shares, in the folder demo_daily_trades. list.files(folder, pattern = ...) lists the file names that match a pattern, here trades_2024-04- followed by two digits, and file.path() joins the folder and the names. The names of the list become the values of file.
use.names = TRUE matches the columns by name, so a file that lists its columns in another order still stacks correctly, while a file with a missing column raises an error, which fill = TRUE would turn into NA values. A silent NA can hide a broken file, so the error is often the safer outcome.
The test reorders the first file’s columns and removes size from the second.
The following box stacks a reordered table and tries a table with a missing column.
[1] "Item 2 has 2 columns, inconsistent with item 1 which has 3 columns. To fill missing columns use fill=TRUE."
Why not grow a table in a loop?
rbind(grown, piece) inside a loop copies the whole growing table on every pass, so stacking 2,000 small tables one by one takes far longer than one call to rbindlist(pieces), which gives the identical table. The times depend on the machine, and the gap grows with the number of tables.
system.time() measures how long an expression takes, and ["elapsed"] keeps the clock time in seconds.
The following box times both ways and checks that they give the same table.
pieces <-lapply(1:2000, function(i) data.table(day = i, value =rnorm(50)))grow_time <-system.time({ grown <-data.table()for (piece in pieces) grown <-rbind(grown, piece)})["elapsed"]once_time <-system.time(once <-rbindlist(pieces))["elapsed"]print(identical(grown, once))
[1] TRUE
print(unname(grow_time > once_time))
[1] TRUE
Your turn
Read only the ticker and size columns of the three files, stack them with their file names, and print the shares per date and ticker.
TipShow answer
select reads only the named columns.
small <-lapply(file.path(folder, files), fread, select =c("ticker", "size"))names(small) <- filesvolume <-rbindlist(small, use.names =TRUE, idcol ="file")volume[, date :=as.IDate(substr(file, 8, 17))]print(volume[, .(shares =sum(size)), by = .(date, ticker)])