[R] random walk w/ reflecting boundary: avoid control construct?

Johannes Hüsing johannes at huesing.name
Wed Oct 24 17:33:31 CEST 2007


Dear expeRts,
recently I asked for a nice way to re-program a problem
without using control constructs such as "for" or
"sapply(1:length(x), ...". Is there a way to program
a random walk with a reflecting boundary without resorting
to such constructs? A working solution is

ranwalk <- function(length, bound) {
    k <- cumsum(sample(c(-1, 1), length, replace=TRUE))
    while( any(abs(k) > bound) ) {
        ri <- min(which(abs(k) > bound))
        k[ri:length] <- k[ri:length] - 2 * sign(k[ri])
    }
    k
}

but it uses "while" and has the same expression in the
"while" statement and the following line. Is there
a sensible way to reprogram it using the "whole object"
approach?



More information about the R-help mailing list