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.

Code: the three made-up daily files
library(data.table)
folder <- "demo_daily_trades"
dir.create(folder, showWarnings = FALSE)
set.seed(4)
for (day in c("2024-04-01", "2024-04-02", "2024-04-03")) {
  ticker <- sample(c("AAA", "BBB"), 1000, replace = TRUE)
  fwrite(data.table(ticker = ticker, price = round(ifelse(ticker == "AAA", 170, 420) * rnorm(1000, 1, 0.005), 2), size = sample(1:500, 1000, replace = TRUE)), file.path(folder, paste0("trades_", day, ".csv")))
}

The following box reads the files, stacks them and counts the trades and shares per day.

files <- list.files(folder, pattern = "^trades_2024-04-\\d{2}\\.csv$")
tables <- lapply(file.path(folder, files), fread)
names(tables) <- files
trades <- rbindlist(tables, use.names = TRUE, idcol = "file")
trades[, date := as.IDate(substr(file, 8, 17))]
print(dim(trades))
[1] 3000    5
print(trades[, .(trades = .N, shares = sum(size)), by = date])
         date trades shares
1: 2024-04-01   1000 251291
2: 2024-04-02   1000 250715
3: 2024-04-03   1000 248886

What if the files’ columns differ?

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.

reordered <- tables[[1]][, .(size, ticker, price)]
print(rbindlist(list(tables[[1]], reordered), use.names = TRUE)[c(1, 1001)])
   ticker  price size
1:    BBB 416.55  189
2:    BBB 416.55  189
print(tryCatch(rbindlist(list(tables[[1]], tables[[2]][, .(ticker, price)]), use.names = TRUE), error = function(e) conditionMessage(e)))
[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.

select reads only the named columns.

small <- lapply(file.path(folder, files), fread, select = c("ticker", "size"))
names(small) <- files
volume <- rbindlist(small, use.names = TRUE, idcol = "file")
volume[, date := as.IDate(substr(file, 8, 17))]
print(volume[, .(shares = sum(size)), by = .(date, ticker)])
         date ticker shares
1: 2024-04-01    BBB 122648
2: 2024-04-01    AAA 128643
3: 2024-04-02    BBB 129805
4: 2024-04-02    AAA 120910
5: 2024-04-03    BBB 125786
6: 2024-04-03    AAA 123100