[R] Create matrices for time series

Gabor Grothendieck ggrothendieck at gmail.com
Thu Apr 14 14:36:46 CEST 2011


On Thu, Apr 14, 2011 at 3:51 AM, mathijsdevaan <mathijsdevaan at gmail.com> wrote:
> Hi list, I would like to use the following data.frame to generate matrices
> over a 3 year moving window:
>
> DF = data.frame(read.table(textConnection("  A  B  C
> 80  8025  1995
> 80  8026  1995
> 80  8029  1995
> 81  8026  1996
> 82  8025  1997
> 82  8026  1997
> 83  8025  1997
> 83  8027  1997
> 84  8026  1999
> 84  8027  1999
> 85  8028  1995
> 85  8029  1998"),head=TRUE,stringsAsFactors=FALSE))
>
> Function to be applied: t(as.matrix(table(DF[,1:2]))) %*%
> as.matrix(table(DF[,1:2]))
>
> I tried this without success:
> n<-rollapply(DF, width = 3, FUN = t(as.matrix(table(DF[,1:2]))) %*%
> as.matrix(table(DF[,1:2])), align = "right")
>

Try this:

Lines <- "  A  B  C
80  8025  1995
80  8026  1995
80  8029  1995
81  8026  1996
82  8025  1997
82  8026  1997
83  8025  1997
83  8027  1997
84  8026  1999
84  8027  1999
85  8028  1995
85  8029  1998"

DF <- read.table(textConnection(Lines), header = TRUE)

f <- function(y) crossprod(table(DF[DF$C %in% y, 1:2]))
years <- sort(unique(DF$C))
e <- as.data.frame(embed(years, 3))
lapply(split(e, e[, 1]), f)




-- 
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