Johannes Hüsing
2007-Oct-24 15:33 UTC
[R] random walk w/ reflecting boundary: avoid control construct?
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?
Charles C. Berry
2007-Oct-24 18:17 UTC
[R] random walk w/ reflecting boundary: avoid control construct?
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
Maybe Matching Threads
- random walk w/ reflecting boundary: avoid control construct? [SEC=UNCLASSIFIED]
- [PATCH] VMX: wbinvd when vmentry under UC
- [PATCH 2/4] CPUIDLE: Avoid remnant LAPIC timer intr while force hpetbroadcast
- using broadvoice and vonage hardware with Asterisk
- Interfacing C++ , MysQL and R