0

I don't understand what is wrong with my code running a loop. Please help

P10<-numeric(2000) 
for(i in 1:2000){
  r <- rnorm(10, 0.03, 0.005)
  P10[i] <- 20 * exp(cumsum(r))
}

Warning in P10[i] <- 20 * exp(cumsum(r)): number of items to replace is not
## a multiple of replacement length
r2evans
  • 141,215
  • 6
  • 77
  • 149
woslx
  • 1
  • 1
    Not sure what you're expected output is supposed to look like. If you rename P10[i] to P, for example, the script runs without warnings. – TJ87 Oct 03 '19 at 20:35
  • 1
    Hi wolsx, it will help if you could provide minimal example with expected output, see https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Bulat Oct 03 '19 at 20:42
  • 1
    It's not clear exactly what you want to do here. The warning is happening because you are trying to assign the list of 10 items created by `exp(cumsum(r))` into a single entry. – cardinal40 Oct 03 '19 at 20:56
  • Here's a suggestion while troubleshooting this. I'll assume that you expect `P10[i]` to contain a single number. Run this manually: `i <- 1; r <- rnorm(10, 0.03, 0.005)`, now look at `r`, it should be a vector (length 10) of numbers. Now run `20 * exp(cumsum(r))`, it is *still* a vector of numbers (length 10), transformed. Now think back to what you expect of `P10[i]` and it supposedly being a single number. What do you need to happen to the vector of 10 numbers? – r2evans Oct 03 '19 at 21:10
  • I figured it out! Thank you everyone – woslx Oct 03 '19 at 23:04

1 Answers1

1

It might be you want to do something like this:

P10 <- lapply(1:2000, function(x) {
  r <- rnorm(10, 0.03, 0.005)
  20 * exp(cumsum(r))
})

P10 <- unlist(P10)

this is similar, but gets you a matrix 10 * 2000

P10 <- replicate(2000, {
  r <- rnorm(10, 0.03, 0.005)
  20 * exp(cumsum(r))
})
Bulat
  • 6,869
  • 1
  • 29
  • 52
  • 1
    Or even *faster*: `20 * exp(apply(matrix(rnorm(10*2000), nr=10), 2, cumsum))`. (It should be faster with larger random-pulls since it is doing just a single random pull instead of 2000 small random pulls.) (FYI: I showed it as `10*2000` to be declarative in the intent of generating enough for the matrix. The `10` should clearly (?) be the same number in `10*` and `nr=10`.) – r2evans Oct 03 '19 at 21:13