[R] setting up zoo objects from a data frame
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Jun 8 17:41:25 CEST 2010
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)
More information about the R-help
mailing list