[R] Loop Issue
Yvan Richard
yvan at dragonfly.co.nz
Fri May 23 07:14:23 CEST 2014
Hi Ricardo
Assuming you have a good reason to use such approach (what are you
trying to do ultimately?), you can just increment your counter when
you get a good value, i.e.:
x <- numeric()
n <- 0
while (n < 10) {
u <- log(runif(1, -1, 2))
if (is.finite(u)) {
n <- n+1
x[n] <- u
}
}
x
On 23 May 2014 12:11, Ricardo Rocha <ricardorocha23 at hotmail.com> wrote:
> Hi everybody.
>
> Consider the following exampling code:
>
> x=numeric()
> for(i in 1:10){
> u=runif(1,-1,2)
> x[i]=log(u)
> }
> This code, in each interation, generates a random value in the (-1,2) interval and then calculates the log of the value.
> When the generated value is less than 0 the log produces a NaN, which gives a warning.
>
> What I want is to make it start over when a warning is produced, in order to repeat it until a positive value is generated and therefore the log is calculated. Logically, would be like: "if there's a warning here, go back at the beginning and start over", without changing the iteration.
>
> Could someone help me with some directions?
>
> Thanks a lot,
>
> Ricardo
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
--
Yvan Richard
DRAGONFLY Science
Physical address: Level 5, 158 Victoria St, Te Aro, Wellington
Postal address: PO Box 27535, Wellington 6141
New Zealand
Ph: 04.385.9285
web page
More information about the R-help
mailing list