Mauro
Mauro

Reputation: 479

R: Error in a Loop, replacement has length zero

I tried to find the solution looking at other questions but no one fits on my needs.

I get the error in this reproducible example:

m <- 0

vectorsd<-  rep(0.2, 183)

dgmean <- -0.41

  rnorm <- as.data.frame(rnorm(183, mean = m, sd = vectorsd))

for (i in 1:length(rnorm$`rnorm(183, mean = m, sd = vectorsd)`))  {
  rnorm[,i] <- rnorm(183, mean = m, sd = vectorsd)
}

simulation1 <- matrix(1,184,183)

beta <- -0.21

##For each column (each value of the forward curve)
for (i in 1:length(simulation1[1,])) {
  ##For each element of a whole column (each day since the starting of the product)
  for (j in 1:length(simulation1[,1])-1) {
    simulation1[j+1,i] <- simulation1[j,i]+rnorm[j,i]+(beta*(simulation1[j,i]-dgmean))
  }
}

I was expecting to get each row of simulation1 as from the second to be substituted with the transformation simulation1[j,i]+rnorm[j,i]+(beta*(simulation1[j,i]-dgmean)) but I get this error instead:

Error in simulation1[j + 1, i] <- simulation1[j, i] + rnorm[j, i] + (beta * : replacement has length zero

What am I missing? I am really burning my brain trying to find the typo/error

Upvotes: 0

Views: 92

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

This runs without any error :

m <- 0
vectorsd<-  rep(0.2, 183)
dgmean <- -0.41
rnorm <- as.data.frame(rnorm(183, mean = m, sd = vectorsd))

for (i in 1:length(rnorm$`rnorm(183, mean = m, sd = vectorsd)`))  {
   rnorm[,i] <- rnorm(183, mean = m, sd = vectorsd)
}

simulation1 <- matrix(1,184,183)
beta <- -0.21

##For each column (each value of the forward curve)
for (i in 1:length(simulation1[1,])) {
  ##For each element of a whole column (each day since the starting of the product)
   for (j in 1:(length(simulation1[,1]) - 1)) {
     simulation1[i,j] <- simulation1[i,j]+rnorm[i,j]+(beta*(simulation1[i,j]-dgmean))
   }
}

Upvotes: 1

Related Questions