Dear R People: I have the following data frame:> str(dog.df)'data.frame': 7 obs. of 2 variables: $ V1: Factor w/ 3 levels "1/1/2000","1/2/2000",..: 1 1 1 2 2 3 3 $ V2: Factor w/ 3 levels "cat","dog","tree": 2 1 3 1 3 2 3> dog.dfV1 V2 1 1/1/2000 dog 2 1/1/2000 cat 3 1/1/2000 tree 4 1/2/2000 cat 5 1/2/2000 tree 6 1/3/2000 dog 7 1/3/2000 tree>I would like to set up 3 time series; one for dog, one for cat, one for tree, such that each runs from 1/1/2000 to 1/3/2000, with 0 if there is no entry for the day. So for instance, I would have: dog.zoo 1/1/2000 1 1/2/2000 0 1/3/2000 1 Any help would be much appreciated. Thanks in advance, Sincerely, Erin -- Erin Hodgess Associate Professor Department of Computer and Mathematical Sciences University of Houston - Downtown mailto: erinm.hodgess at gmail.com
Am 08.06.2010 16:52, schrieb Erin Hodgess:> > I would like to set up 3 time series; one for dog, one for cat, one > for tree, such that each runs from 1/1/2000 to 1/3/2000, with 0 if > there is no entry for the day. > > >Before using zoo or zooreg you should transform your data.frame as such as that you have one column for each time series you want to have afterwards. have a look at ?reshape to do so. little example: test<-data.frame(date=c("2001/01/01","2001/01/01","2001/01/02","2001/01/02"),animal=c("dog","cat","dog","cat"),data=1:4) test.w<-reshape(test,idvar="date",timevar="animal",direction="wide") test.w then you can do the zoo stuff, e.g. with ?zooreg if you have a "regular" series. It will transform automatically into a multiple time series. hth Stefan
The first time I posted this it got held up for approval so I am trying it again. Hopefully this time it gets through right away. As with your prior post we can use read.zoo(..., split=...). Alternatives are reshape and reshape::cast. # read data into DF Lines <- "V1 V2 1 1/1/2000 dog 2 1/1/2000 cat 3 1/1/2000 tree 4 1/2/2000 cat 5 1/2/2000 tree 6 1/3/2000 dog 7 1/3/2000 tree" DF <- read.table(textConnection(Lines), header = TRUE) DF$V1 <- as.Date(DF$V1, "%m/%d/%Y") # 1. using zo library(zoo) d <- read.zoo(cbind(DF, 1), split = 2) do.call(merge, c(d, fill = 0)) # 2. using reshape DF2 <- with(DF, data.frame(Date = V1, V2, 1)) r <- reshape(DF2, dir = "wide", idvar = "Date", timevar = "V2") colnames(r) <- c("Date", sub("X1.", "", colnames(r))[-1]) r[is.na(r)] <- 0 r # 3. using the reshape package (where DF2 is as in #2) library(reshape) cast(formula = Date ~ V2, data = DF2, value = "X1", fill = 0)