Skip to content
Prev 256373 / 398502 Next

Yearly aggregates and matrices

On Sat, Apr 9, 2011 at 5:14 AM, mathijsdevaan <mathijsdevaan at gmail.com> wrote:
First we use read.zoo to reform DF into a multivariate time series and
use rollapply (where we have used the devel version of zoo since it
supports the partial= argument on rollapply).  We then reform each
resulting row into a matrix converting each row of each matrix to
proportions.  Finally we form the desired scaled cross product.

# devel version of zoo
install.packages("zoo", repos = "http://r-forge.r-project.org")
library(zoo)

z <- read.zoo(DF, split = 2, index = 3, FUN = identity)

sum.na <- function(x) if (any(!is.na(x))) sum(x, na.rm = TRUE) else NA
r <- rollapply(z, 3,  sum.na, align = "right", partial = TRUE)

newDF <- lapply(1:nrow(r), function(i)
	prop.table(na.omit(matrix(r[i,], nc = 4, byrow = TRUE,
		dimnames = list(unique(DF$B), names(DF)[-2:-3]))[, -1]), 1))
names(newDF) <- time(z)

lapply(mats, function(mat) tcrossprod(mat / sqrt(rowSums(mat^2))))