Question

I have the following R code to load xts timeseries from multiple files and merge them in a single xts matrix:

load.files = function(dates, filenames) {
  for( i in 1:length(dates) ) {
  # load and merge each xts block
  ts.set = load.single.file(dates[i], filenames[i])
  if( i == 1 )
    ts.all = ts.set
  else
    ts.all = rbind(ts.all, ts.set)
}

return(ts.all)

Is there a way to

  1. Avoid the if/else statement required to initialize the very first ts.set?
  2. Avoid the for loop altogether?
Was it helpful?

Solution

I often use a construct like this, which avoids explicit loop construction.

The strategy is to first read the files into a list of data.frames, and to then rbind together the elements of that list into a single data.frame. You can presumably adapt the same logic to your situation.

filenames <- c("a.csv", "b.csv", "c.csv")
l <- lapply(filenames, read.csv)
do.call("rbind", l)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top