I create the following range:
x <- seq(0,22)
Now I want to get some expected poisson estimations:
for (val in x) {
vec[val]<-(dpois(val,6.298387))*124
}
I want also the estimation for val = 0
(dpois(0,6.298387))*124
However, the vector "vec" obtained previously starts at val = 1.
How can I force the loop to take also values = 0?
CodePudding user response:
Since R is 1-indexed, there is no such thing as vec[0]
. The first valid index of vec
is vec[1]
, so you probably intended
x <- seq(0,22)
vec <- numeric()
for (val in x) {
vec[val 1] <- dpois(val, 6.298387) * 124
}
vec
#> [1] 2.280694e-01 1.436469e 00 4.523719e 00 9.497378e 00 1.495454e 01
#> [6] 1.883790e 01 1.977473e 01 1.779270e 01 1.400816e 01 9.803203e 00
#> [11] 6.174437e 00 3.535363e 00 1.855590e 00 8.990174e-01 4.044542e-01
#> [16] 1.698273e-01 6.685238e-02 2.476836e-02 8.666707e-03 2.872962e-03
#> [21] 9.047512e-04 2.713559e-04 7.768656e-05
However, the loop is not necessary, since dpois
is vectorized like many R functions. Therefore the above code simplifies to this one-liner:
dpois(0:22, 6.298387) * 124
#> [1] 2.280694e-01 1.436469e 00 4.523719e 00 9.497378e 00 1.495454e 01
#> [6] 1.883790e 01 1.977473e 01 1.779270e 01 1.400816e 01 9.803203e 00
#> [11] 6.174437e 00 3.535363e 00 1.855590e 00 8.990174e-01 4.044542e-01
#> [16] 1.698273e-01 6.685238e-02 2.476836e-02 8.666707e-03 2.872962e-03
#> [21] 9.047512e-04 2.713559e-04 7.768656e-05
Created on 2022-07-22 by the reprex package (v2.0.1)