rollapply 可以返回矩阵列表吗? [英] Can rollapply return a list of matrices?

查看:25
本文介绍了rollapply 可以返回矩阵列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用滚动窗口生成协方差矩阵(和均值向量).但是在我所有的尝试中,rollapply 将来自 cov 的协方差矩阵堆叠起来,并且用完预分配的空间(例如,如果我的原始数据有 40 个观察值,则 rollapply 不能返回超过 40 行).

I would like to generate covariance matrices (and mean vectors) using a rolling window. But in all my attempts rollapply stacks the covariance matrices from cov and runs out of pre-allocated space (e.g., if my original data have 40 observations, then rollapply can't return more than 40 rows).

有没有办法让 rollapply 返回矩阵列表?或者返回一个比原始 data.frame 大的 data.frame,我可以手动拆分成一个列表?我的最终目标是获取一个面板,将面板拆分为一个单独的 data.frame 列表,计算每个数据框的滚动协方差和均值,然后使用这些协方差列表和下游均值与一群人进行比较.

Is there a way that I can get rollapply to return a list of matrices? Or to return a data.frame that is larger than the original data.frame, which I can manually split into a list? My end goal is to take a panel, split the panel into a list of individual data.frames, calculate the rolling covariances and means for each data frame, then use these lists of covariances and means downstream to compare to a bunch of individuals.

这是一些代码.我的问题是 my.fun 不会从所有协方差矩阵计算中返回数据.编写自己的 rollapply 是我最好的选择吗?或者我自己的 cov 返回一个我转换回矩阵的向量?谢谢!

Here is some code. My problem is that my.fun won't return data from all covariance matrix caluclations. Is my best option to code my own rollapply? Or my own cov that returns a vector that I convert back to a matrix? Thanks!

library("zoo")
data.df <- data.frame(sic = rep(1:10, each = 40),
                      year = rep(1:40, len = 10*40),
                      one = rnorm(10*40),
                      two = 2*rnorm(10*40),
                      three = 3*rnorm(10*40))
data.list <- split(data.df, data.df$sic)
data.list <- lapply(data.list, zoo)
my.fun <- function(x) {
    x <- x[, c("one", "two", "three")]
    rollapply(x,
              width = 10, 
              FUN = cov,
              by.column = F, 
              align = "right")
}
cov.list <- lapply(data.list, FUN = my.fun)

推荐答案

在看了 rollapply.zoo 代码后,我认为没有办法让它做你想做的事.虽然滚动你自己的函数并不难(双关语).

After glancing at the rollapply.zoo code, I don't think there's a way to make it do what you want. Rolling your own function isn't that difficult though (pun intended).

rollcov <- function(x, width=10) {
  len <- NROW(x)
  add <- rep(1:(len-width)-1,each=width)
  seq.list <- split(rep(1:width,len-width)+add, add)
  lapply(seq.list, function(y) cov(x[y,]))
}

rollcov(data.list[[1]][,c("one","two","three")],10)
all <- lapply(data.list, function(x) rollcov(x[,c("one","two","three")],10))

这篇关于rollapply 可以返回矩阵列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆