Skip to content
Prev 309192 / 398506 Next

Filling a covariance matrix

Hi Eric,
On Tue, Oct 23, 2012 at 10:59 AM, emorway <emorway at usgs.gov> wrote:
Thanks for the reproducible example.  I don't have time to provide a
complete solution, but this should get you started and hopefully give
you some ideas:

# create a list of xts objects that only contain data for one day
xs <- split(x, "days")
# initialize the covariance matrix
xcov <- matrix(0, length(xs)*2, length(xs)*2)
rownames(xcov) <- colnames(xcov) <-
  c(sprintf("Q%d",seq_along(xs)), sprintf("SC%d",seq_along(xs)))
# use a double-for loop to fill it in
for(i in seq_along(xs)) {
  for(j in seq_along(xs)) {
    xcov[paste0("Q",i),paste0("Q",j)] <- # same as below
    xcov[paste0("Q",j),paste0("Q",i)] <- cov(xs[[i]]$Q, xs[[j]]$Q, use="pair")
    xcov[paste0("Q",i),paste0("SC",j)] <- # same as below
    xcov[paste0("Q",j),paste0("SC",i)] <- cov(xs[[i]]$Q, xs[[j]]$SC, use="pair")
    xcov[paste0("SC",i),paste0("SC",j)] <- # same as below
    xcov[paste0("SC",j),paste0("SC",i)] <- cov(xs[[i]]$SC, xs[[j]]$SC,
use="pair")
  }
}
Please include some context if you reply via nabble.  This is a
mailing list, not a forum, and nabble doesn't quote the previous post
by default, which can be frustrating for mailing list subscribers.
Best,
--
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com