Nils
Nils

Reputation: 173

Dimension in for loop not correct

I'm struggling with a problem for two days now and I just don't get it.

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
}

The loop should create a rolling window of covariance matrices. This is why I need the Sigma to move by 4. Does R understand the for loop for k and l?

Upvotes: 1

Views: 58

Answers (1)

Oliver
Oliver

Reputation: 312

Yes, R understandes the loop for k and l.

Taking your code and adding oppening and closing {} we get:

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
    }
  }
}

Side note: Allways good to use set.seed() when using random number generators in examples.

The loop works but results in the following error:

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

As I understand your code you want to calculate step by step a 4x4 cov matrix, correct? But the loop tries to save this 4x4 using Sigma[k:l, ] It works for the first iteration, i.e. k = 1 and l = 4. But with the the next iteration l takes the value of 8 and now the code says: Sigma[1:8, ] = cov(H_t[1:i,1:4])

Hope this helps.

Edit in response to the comment:

This works for a rolling window backwards looking (window of 4 observations max):

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])
}

From the comments it now is clear to me it should be a growing window:

# 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])
}

Upvotes: 2

Related Questions