[R] building time series/zoo/its from a data frame

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jun 2 23:00:03 CEST 2010


r-help seems to have rejected the first attempt at sending this so I
am trying again.

read.zoo has a split= argument which lets you read in the data and
split it all at the same time.  You can also use it on a data frame.
Due to a bug which is fixed in the development version, you will need
the development version of zoo which you can access as shown below.
First we show reading it in using read.zoo and splitting it at the
same time.  Next we assume its already been read in as a data frame in
which case we can also use read.zoo on a data.frame:

library(zoo)
source("http://r-forge.r-project.org/scm/viewvc.php/*checkout*/pkg/zoo/R/read.zoo.R?revision=717&root=zoo")

Lines <- "date        cond freq
1  04/01/09       Fever   12
2  04/02/09       Fever   11
3  04/03/09       Fever   10
4  04/04/09       Fever   13
5  04/05/09       Fever    6
6  04/01/09        Rash    6
7  04/02/09        Rash   10
8  04/03/09        Rash    9
9  04/04/09        Rash   10
10 04/05/09        Rash    8
11 04/01/09 Respiratory   12
12 04/02/09 Respiratory    9
13 04/03/09 Respiratory    6
14 04/04/09 Respiratory   11
15 04/05/09 Respiratory   11"

# 1. reading it in and splitting at the same time
z <- read.zoo(textConnection(Lines), header = TRUE, split = "cond",
format = "%m/%d/%y")

# or, 2. if its already a data frame such as this one we can still use read.zoo
DF <- read.table(textConnection(Lines), header = TRUE)
z2 <- read.zoo(DF, split = 2, format = "%m/%d/%y")



More information about the R-help mailing list