I'm still pretty new to R programming, and I've read a lot about replacing for-loops, particularly with the apply functions, which has been really useful in making my code more efficient. However, in some of the programs I'm trying to create, I have for-loops where each loop must be carried out in order, because the effects of one loop affect what happens in the next loop, and as far as I'm aware this cannot be achieved with, for example, lapply(). An example of this sort of for-loop:
p <- 1
for (i in 1:x) {
p <- p + sample(c(1, 0), prob = c(p, 1), size = 1)
}
Is there a way to replace this kind of loop?
Thanks for your time, everyone!
This kind of logic is known as reduction or fold. Consequently it’s solved not by lapply
(or similar), which is an example of a mapping, but by Reduce
:
p = Reduce(function (a, b) a + sample(c(1, 0), prob = c(a, 1), size = 1),
seq_len(x), initial_value)
Note that the argument b
in this case isn’t used — this corresponds to your loop variable i
, which is likewise not used.