Re: [R] Infinite loop

From: jim holtman <jholtman_at_gmail.com>
Date: Tue, 22 Mar 2011 12:59:54 -0400

The simple thing to do is to put a sanity counter in the 'repeat' statement and if you have been through it a certain number of times, then exit. Anytime you have a loop that might run forever, you should have some sanity/watchdog timer on it.

On Tue, Mar 22, 2011 at 11:02 AM, Hosack, Michael <mhosack_at_state.pa.us> wrote:
> R experts,
>
> Hello, I am trying to sample a vector 1:40 without replacement such that no element in the new vector
> is within 7 units of either of its immediate neighbors. This is part of a larger program I am working
> on. The following code works well about 65 % of the time (14/40). The problem I encounter happens when
> the last element remaining to be sampled from the vector STRATA is within 7 digits +- of the last element
> in the vector s1, at which point an infinite loop occurs. At least that's what I think is happening.
> Any help would be greatly appreciated.
>
> Thank you,
>
> Mike
>
> require(IRanges)
> STRATA <- 1:40
> s1 <- sample(STRATA, 1)
> for (i in seq(from = 1, to = 39, by = 1)){
>  repeat{
>    tmp <- sample(STRATA, 1)
>    if (!any(s1 == tmp) & !any(as.vector(IRanges(s1[length(s1)]-7, s1[length(s1)]+7)) %in% tmp)) break
>    }
>  s1 <- c(s1,tmp)
> }
> s1
>
> ______________________________________________
> 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.
>

-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?

______________________________________________
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.
Received on Tue 22 Mar 2011 - 17:04:06 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 22 Mar 2011 - 18:10:23 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive