[R] Avoiding Loops When Iterating Over Statement That Updates Its Input

Alan Lue alan.lue at gmail.com
Wed May 26 08:43:37 CEST 2010

Since `for' loops are slow in R, and since `apply' functions are
faster, I was wondering whether there were a way to use an apply
function—or to otherwise avoid using a loop—when iterating over a
statement that updates its input.

For example, here's some such code:

r.seq <- 2 * (1 / d$Dt[1] - 1)
for (i in 2:nrow(d)) {
  rf <- uniroot(bdt.deviation, interval=c(0, 1), D.T=d$Dt[i], r.prior=r.seq)
  r.seq <- append(r.seq, rf$root)

The call to `uniroot()' both updates `r.seq' and reads it as input.
We could save the output of each invocation of `uniroot()' and
concatenate it later, but is there a better way to write this (i.e.,
to execute more quickly) while updating `r.seq' in each iteration?


More information about the R-help mailing list