[R] Help with creating a ts (time series) object with daily sampling values
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Mar 24 21:54:43 CET 2011
On Thu, Mar 24, 2011 at 3:25 PM, Pamela Allen <allen_pam at hotmail.com> wrote:
>
>
>
> Hi All,
>
>
>
> I have a data set of daily measurements of river flow.
> I would like to create a “ts” object from this data.
>
>
>
> Here’s a sample data set:
>
> date <- as.Date(c(1:300), format="%Y")
>
> year=as.numeric(format(date, format = "%Y"))
>
> month=as.numeric(format(date, format = "%m"))
>
> julianday=as.numeric(format(date, format = "%j"))
>
> week=floor(julianday/7)
>
> flow <- sin(2*pi/53*c(1:300))
>
> data <- cbind.data.frame(date,year,month,julianday,week,
> flow)
>
>
>
> I know how to do this with exact dates using the irts
> package:
>
> install.packages("tseries")
>
> library(tseries)
>
> data=cbind.data.frame(data,posixlt.time=as.POSIXlt(data$date,
> "PDT")) ##To create dates based on POSIXlt
>
> data.irts=irts(data$posixlt.time, data$flow)
>
>
>
> But I would like the time series object to be in the “ts”
> format. I tried using this code:
>
>
>
> data.ts=ts(data$flow, start=c(data$year[1],
> data$julianday[1]), frequency=365)
>
>
>
> Which does work, but I worry about the influence of leap
> years, since my data set is quite large. What is the way to properly code
> a ts object with daily measurements? Thank you!
>
>
ts does not work the best with dates. You could use the internal
representation of the date as per Date class:
set.seed(123)
tt <- ts(rnorm(20), start = Sys.Date())
but then if you need the dates you will have to get them via:
as.Date(as.numeric(time(tt)), origin = "1970-01-01")
The zoo package and a number of other packages can handle time series
with dates:
library(zoo)
z <- zooreg(rnorm(20), start = Sys.Date())
time(z) # show the dates
One can convert zoo to ts although you will lose the "Date" class
since its not representable in ts:
as.ts(z)
You can also convert back
zz <- as.zoo(tt)
class(time(zz)) <- "Date"
--
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