[R] random walk w/ reflecting boundary: avoid control construct?
Charles C. Berry
cberry at tajo.ucsd.edu
Wed Oct 24 20:17:52 CEST 2007
On Wed, 24 Oct 2007, Johannes Hüsing wrote:
> 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?
Does this satisfy your 'sensible' sensibility?
ranwalk2 <-
function(length., bound) {
k <- cumsum(sample(c(-1, 1), length., replace=TRUE))
lk <- rep( c( 0:bound, (bound-1):(-bound), (1-bound):(-1)),
length=max(abs(k))+1)
sign(k)*lk[ 1 + abs(k) ]
}
HTH,
Chuck
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list