2

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?
4

1 回答 1

3

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)
于 2012-01-04T21:45:08.867 回答