Create matrices for time series

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Create matrices for time series

mdvaan
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")

Any suggestions? Thanks a lot!
Reply | Threaded
Open this post in threaded view
|

Re: Create matrices for time series

Gabor Grothendieck
On Thu, Apr 14, 2011 at 3:51 AM, mathijsdevaan <[hidden email]> 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

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.