Add elements to a vector in R with while loop -


suppose vector follow:

fruit = c("apple", "orange") 

i sample 1 fruit @ time , store chosen fruit in vector.

chosen=sample(fruit, size = 1, replace = true) 

suppose want continue sampling until total number of oranges 2 more of apples, i'm having trouble combining samples single vector.

i = 1 keepgoing = true while(keepgoing){   i=sample(fruit, size = 1, replace = true)   i+1=sample(fruit, size = 1, replace = true)   fruitlist=rbind(i, i+1)   if(sum(fruitlist=="orange")-sum(fruitlist=="apple")==2){   keepgoing = false}   = +2   } 

since sample units independent (probability of later units not depend on probability of earlier units, being 0.5 in case), can use strategy. instead of growing sample, can draw large(r) sample first, , cut off @ point our desired condition satisfied:

makesample <- function(n=20) {      fruit <- c("apple", "orange")      full.sample <- sample(x = fruit, size = n, replace = true)     apples  <- cumsum(full.sample == "apple")     oranges <- cumsum(full.sample == "orange")     diff <- oranges - apples      exit.position <- match(2l, diff)     if (is.na(exit.position))         stop("the condition specified not achieved, try again or increase n")     result <- head(full.sample, exit.position)     return(result) } 

the function simple really. draws large (superset) sample of desired length, default 20. 2 logical vectors created (full.sample == "orange" , full.sample=="apple"), amount of apples , oranges in each successive step calculated cumsum(), since true equal 1 (fruit present) , false 0 (fruit absent). take difference between vectors , see whether @ point difference satisfies our condition. if yes, function returns resulting sample wanted. if not, throws error urging try again or increase n.

this should more efficient on larger samples, , can adjusted more complex conditions. when n small, there chance won't result, opposed loop solution. chances approaching 1 n increases. wrap makesample() in function make sure result.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -