r - Loop While condition is TRUE -


i trying generate n random numbers sum less 1.

so can't run runif(3). can condition each iteration on sum of values generated point.

the idea start empty vector, v, , set loop such each iteration, i, runif() generated, before accepted element of v, i.e. v[i] <- runif(), test sum(v) < 1 carried out, , while false last entry v[i] accepted, but if true, sum greater 1, v[i] tossed out of vector, , iteration i repeated.

i far implementing idea, resolve along lines of similar follows. it's not practical problem, more of exercise understand syntax of loops in general:

n <- 4 v <- 0  (i in 1:n){     rdom <- runif(1)     if((sum(v) + rdom) < 1) v[i] <- rdom     }     # keep trying before moving on iteration + 1???? <- stays i????? }  

i have looked while (actually incorporated while function in title); however, need vector have n elements, stuck if try tells r add random uniform realizations elements of vector v while sum(v) < 1, because can end less n elements in v.

here's possible solution. it doesn't use while more generic repeat. edited use while , save couple of lines.

set.seed(0) n <- 4 v <- numeric(n) <- 0 while (i < n) {   ith <- runif(1)   if (sum(c(v, ith)) < 1) {     <- i+1     v[i] <- ith   } } v # [1] 0.89669720 0.06178627 0.01339033 0.02333120 

using repeat block, must check condition anyways, but, removing growing problem, similar:

set.seed(0) n <- 4 v <- numeric(n) <- 0 repeat {   ith <- runif(1)   if (sum(c(v, ith)) < 1) {     <- i+1     v[i] <- ith   }   if (i == 4) break }  

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -