[R] Loop Issue

arun smartpink111 at yahoo.com
Fri May 23 11:40:00 CEST 2014


Hi,
You may also try:
fun1 <- function(n, repl, val1, val2) {
    mat1 <- suppressWarnings(replicate(repl, log(runif(n, val1, val2))))
    mat1[!is.na(mat1)][seq(n)]
}

#Jim's function
fun2 <- function(init, final, val1, val2) {
    i <- init
    while (i < final) {
        u <- runif(1, val1, val2)
        if (u >= 0) {
            x[i] <- log(u)
            i <- i + 1
        }
    }
    x
}


set.seed(49)
 x1 <- fun1(10,3,-1,2)
 set.seed(49)
 x2 <- fun2(1,11,-1,2)
 identical(x1,x2)
#[1] TRUE

###Speed comparison
set.seed(58)
 system.time(x1 <- fun1(1e5,100, -1,2))
#   user  system elapsed 
#  1.392   0.105   1.500 


set.seed(58)
 system.time(x2 <- fun2(1,1e5+1,-1,2))
#   user  system elapsed 
# 31.930   0.988  32.973

identical(x1,x2)
#[1] TRUE


A.K.








On Friday, May 23, 2014 4:19 AM, Jim Lemon <jim at bitwrit.com.au> wrote:
On Thu, 22 May 2014 09:11:43 PM Ricardo Rocha 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?
> 
Hi Ricardo,
Perhaps what you want is something like this:

i<-1
while(I < 11) {
u<-runif(1,-1,2)
if(u >= 0) {
  x[i]<-log(u)
  i<-i+1
}
}

Jim


______________________________________________
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.




More information about the R-help mailing list