简体   繁体   English

在R中创建矩阵列表

[英]Creating list of matrices in R

> fact.cov <- matrix(NA,ncol(fact.weight),ncol(fact.weight))

> for (row in 15:nrow(fact.weight)) {
    >> fact.cov[[row]] <- var(fact.wealth.return[(row-1):row,])
}

When I run this code I get the following error message: 当我运行此代码时,出现以下错误消息:

Error in fact.cov[[row]] <- var(fact.wealth.return[(row - 1):row, ]) : 
  more elements supplied than there are to replace

For each point in time (row), I need to create a covariance matrix. 对于每个时间点(行),我需要创建一个协方差矩阵。 Do someone knows how to do this? 有人知道该怎么做吗?

Thank you in advance! 先感谢您!

This could be helpful: 这可能会有所帮助:

fact.cov <- list()
for (k in 15:fact.weight) {
 fact.cov[[k]] <- var(fact.wealth.return[(k-1):k,])    
};rm(k)

However, you should provide more details in order for your code to be reproduceable (eg what is fact.wealth.return or fact.weight ). 但是,您应该提供更多详细信息以使代码可重现(例如,什么是fact.wealth.returnfact.weight )。

It's hard to tell what exactly you seek to accomplish without understanding your data. 在不了解数据的情况下很难说出您到底想完成什么。 But you can easily create an empty list, and then assign a matrix to each of the list's elements, thus obtaining a list of matrices. 但是您可以轻松地创建一个空列表,然后为该列表的每个元素分配一个矩阵,从而获得矩阵列表。 I would encourage creating an empty list of determined size, because this is generally a better use of memory and can be faster. 我鼓励创建一个确定大小的空列表,因为这通常可以更好地利用内存,并且可以更快。

listOfMatrices <- vector("list", 10)
for (i in 1:10) {
  listOfMatrices[[i]] <- matrix(NA, nrow=2, ncol=3)
}

The output of this will be a list of length 10 , and each element of this list will be a matrix with 2 rows and 3 columns. 此输出将是一个长度为10的列表,此列表的每个元素将是一个具有23列的矩阵。 Each matrix will be populated by NA s. 每个矩阵将由NA填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM