I can store values in a loop to a vector effectively when writing a loop likeso:
z = 0.5
x <- vector("numeric", 10)
for(i in 1:10){
x[i] <- z - i/10
}
>[1] 0.4 0.3 0.2 0.1 0.0 -0.1 -0.2 -0.3 -0.4 -0.5
However, when I use a sequence of numbers instead of a colon separator likeso:
z = 0.5
x <- vector("numeric", 20)
for(i in seq(0.05, 1, 0.05)){
x[i] <- z - i
}
>[1] -0.5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
It fails to return me a vector for each iteration of i
, why does it do this and how can I get the loop to work effectively with seq()
?
CodePudding user response:
Your index also becomes a double, that's the issue. You may define a vector I
with the numbers and loop over the seq
uence of indices. Subset both the I
and the result x
with i
.
z <- 0.5
x <- vector("numeric", 20)
I <- seq(0.05, 1, 0.05)
for (i in seq(I)) {
x[i] <- z - I[i]
}
x
# [1] 0.45 0.40 0.35 0.30 0.25 0.20 0.15 0.10 0.05
# [10] 0.00 -0.05 -0.10 -0.15 -0.20 -0.25 -0.30 -0.35 -0.40
# [19] -0.45 -0.50
Just in case that was not just a simplified example of something, since R is vectorized you may also do just
z - seq(0.05, 1, 0.05)
# [1] 0.45 0.40 0.35 0.30 0.25 0.20 0.15 0.10 0.05
# [10] 0.00 -0.05 -0.10 -0.15 -0.20 -0.25 -0.30 -0.35 -0.40
# [19] -0.45 -0.50