[R] Inputing data from multiple files as time series objects

Sean Davis sdavis2 at mail.nih.gov
Fri Nov 11 15:24:31 CET 2005


On 11/11/05 9:07 AM, "Constantine Tsardounis" <costas.magnuse at gmail.com>
wrote:

> Hello to everyone,...
> 
> I am a new R ambitious user. I would like to be the first at my
> department using R, but I have encountered a difficulty during the
> last days that I cannot overcome reading help() and searching over the
> net.
> Problem:
> I have multiple files with financial data like the following (header
> included):
> E.g.:
> filename: AOL.txt
> aol.txt
> 4
> 3
> 5
> 3...
> 
> filename: IBM.txt
> ibm.txt
> 6
> 2
> 5
> 2...
> 
> I would like to input these data in R as time-series objects with
> their corresponding names automatically, so that I can manipulate them
> (exempli gratia plot acf, pacf, differntiate them, make adf tests,
> etc)
> For example: I could do that by hand using:
> AOL <- ts(read.table(AOL.txt, header = TRUE))))
> IBM <- ts(read.table(IBM.txt, header = TRUE))))
> but is there another way to achieve the same actions as above with a
> more versatile way? (for example loops?)
> Or would you suggest inputing these data with another way or as other objects?

myts <- list()
mydir <- 'path/to/files'
# put all files in the same directory
myfiles <- dir('path/to/files',pattern='.txt')
for (i in myfiles) {
  myts[[sub('.txt','',i)]] <-
    ts(read.table(paste(mydir,myfiles,sep='/'),header=T))
}

This will give you back a list of ts objects based on all txt files in a
directory.  I haven't tested the code, but I hope you get the idea.

Sean




More information about the R-help mailing list