【问题标题】:Dimension in for loop not correctfor 循环中的尺寸不正确
【发布时间】:2015-12-18 09:44:46
【问题描述】:

我现在正在为一个问题苦苦挣扎两天,但我就是不明白。

input <- H_t <- matrix(rep(0,2515), 2515, 4)
H_t[,1]=rnorm(2515)
H_t[,2]=rnorm(2515)
H_t[,3]=rnorm(2515)
H_t[,4]=rnorm(2515)

d=dim(H_t)
Sigma=matrix(0,d[1]*4,4) 
for( i in 2:d[1])
for(k in seq(from=1, to=10057, by=4))
for(l in seq(from=4, to=10060, by=4))
{
Sigma[k:l ,1:4]=cov(H_t[1:i,1:4]) ##here is the problem of dimensions
}

循环应该创建一个协方差矩阵的滚动窗口。这就是为什么我需要 Sigma 移动 4。R 是否理解 k 和 l 的 for 循环?

【问题讨论】:

  • 你在 for 循环的最后一个分号。那是对的吗? for(l in seq(from=4, to=10060, by=4));
  • 对不起,没有。
  • 第一行出现错误...你想用rnorm 或类似的东西替换数字吗?
  • 您还想获得什么协方差?在初始矩阵(输入)之间,由行子集i-4i 以及其他什么?
  • 我想要 H_t 与 1:i 的协方差,所以 1:2、1:3、1:4.........1:2515。这样您就可以为 2515 个步骤中的每一个步骤提供一个 4x4 矩阵。

标签: r dimensions


【解决方案1】:

是的,R 理解 k 和 l 的循环。

获取您的代码并添加打开和关闭 {} 我们得到:

set.seed(101)
input <- H_t <- matrix(rep(0,2515), 2515, 4)
H_t[,1]=rnorm(2515)
H_t[,2]=rnorm(2515)
H_t[,3]=rnorm(2515)
H_t[,4]=rnorm(2515)

d=dim(H_t)
Sigma = matrix(0, d[1]*4, 4)

for(i in 2:d[1]){
  # i <- 2
  for(k in seq(from=1, to=10057, by=4)){
    # k <- 1
    for(l in seq(from=4, to=10060, by=4)){
      # l <- 4
      Sigma[k:l ,1:4] = cov(H_t[1:i,1:4]) ##here is the problem of dimensions
    }
  }
}

旁注:在示例中使用随机数生成器时使用 set.seed() 总是很好。

循环有效,但导致以下错误:

number of items to replace is not a multiple of replacement length

据我了解,您希望逐步计算 4x4 cov 矩阵,对吗? 但是循环尝试使用来保存这个 4x4 Sigma[k:l, ] 它适用于第一次迭代,即 k = 1 和 l = 4。但在下一次迭代中 l 取值 8,现在代码显示: Sigma[1:8, ] = cov(H_t[1:i,1:4])

希望这会有所帮助。

根据评论进行编辑:

这适用于向后看的滚动窗口(最多 4 个观察的窗口):

n <- 15
set.seed(101)
input <- H_t <- matrix(rep(0,n), n, 4)
H_t[,1] <- rnorm(n)
H_t[,2] <- rnorm(n)
H_t[,3] <- rnorm(n)
H_t[,4] <- rnorm(n)

d <- dim(H_t)
Sigma <- matrix(0, (n-1)*4, 4)

k <- seq(from=1, to=(n-1)*4 - 3, by=4)
length(k)
l <- seq(from=4, to=(n-1)*4, by=4)
length(l)
# start the rolling and calculate the cov backwards looking
for(i in 1:(n-1)){
  present <- i + 1
  past <- present - 3
  if(past < 1) past <- 1
  Sigma[k[i]:l[i], ] = cov(H_t[past:present, 1:4])
}

从 cmets 来看,我现在很清楚它应该是一个增长的窗口:

# start the growing and calculate the cov backwards looking
for(i in 1:(n-1)){
  present <- i + 1
  Sigma[k[i]:l[i], ] = cov(H_t[1:present, 1:4])
}

【讨论】:

  • 是的!我希望第二次迭代需要 Sigma[5:8, ] 和第三次 Sigma[9:12, ] 等等。如果我自己动手修复这些值,它会起作用。但为什么不在循环中呢?
  • 它在第一行工作,但最后一个 4x4 矩阵应该是 cov(H_t[1:15,1:4]) 这不是这种情况。我有同样的问题以及为什么我将代码更改为上面的代码。
  • 因此您不是在寻找滚动窗口,而是在寻找扩展窗口!只需删除 past 并在其中放一个 1。
  • 是的,很抱歉这个错误!感谢您的帮助!
猜你喜欢
  • 2012-10-28
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多