[R] Adding dates to time series

Gabor Grothendieck ggrothendieck at gmail.com
Mon May 16 02:50:37 CEST 2011


On Sun, May 15, 2011 at 2:42 PM, Bazman76 <h_a_patience at hotmail.com> wrote:
> Hi there,
>
> I have a spreadsheet in excel which consists of first column  of dates and
> then subsequent columns that refer to prices of different securities on
> those dates. (the first row contains each series name)
>
> I saved the excel file as type csv and then imported to excel using
>
> prices=read.csv(file="C:/Documents and Settings/Hugh/My Documents/PhD/Option
> prices.csv",header = TRUE, sep = ",")
>
> This creates the correct time series data
>
> x<-ts(prices[,2])
>
> but does not have the dates attached.
>
> However the dates refer to working days. So although in general they
> represent Monday-Friday this is not always the case because of holidays etc.
>
> How then can I create a time series where the dates are read in from the
> first column of the csv file? I can not find an example in R documentation
> where this is done?
>

Lines <- "time,s
2003-01-01,1.4292491
2003-02-01,-1.0713998
2003-03-01,-0.4738791"

library(zoo)

# F <- "C:/Documents and Settings/Hugh/My Documents/PhD/Option prices.csv"
# z <- read.zoo(F, header = TRUE, sep = ",")

# in reality we would read from the file as shown in the comments above
# but here we do it this way so we can just copy it and paste it
# verbatim into the R session

z <- read.zoo(textConnection(Lines), header = TRUE, sep = ",")

If you want xts then:

library(xts)
x <- as.xts(z)

Note that ts is not good for dates so use zoo or xts.

See ?read.zoo in the zoo package.

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list