> -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] > On Behalf Of Manos Spanakis > Sent: Saturday, November 23, 2013 1:48 AM > To: R-help@r-project.org > Subject: [R] Randomize two categories testing a specific condition R > version 3.0.2 windows 32 bit > > Hello everyone I am new to R. At this time I am trying to create a vector > so i can randomize two categories a,b under the following conditions : > Take a random x from random uniform(0,1) if x<0.5 then the vector takes > value a else takes b . This continues until the number of a's-the number > of > b's > 2 at this point i want to change the possibility that a's and b's > are > assigned to the vector to 0.2 (if x<0.2 then a). This probability i want > to > change again if the number of b's - the number of a's > 2 to 0.8(if x<0.8 > then a). However because i have random numbers i may have the above > situation vice versa. (first b's-a's>2 then a's-b's>2) .finally sth like > vector<- a,b,a,a,a,b,b,a . I thought to use a for loop and this is my code > ; > > set.seed(10) > x<- rep(NA, 20) > tmp<- rep(FALSE, 20)for(i in 1:20) { > x[i]<- runif(1) > tmp<- x[i]<0.5if(2 * sum(tmp) - i + 1 > 2) { > tmp[i]<- x[i]<0.2} else { > tmp[i]<- x[i]<0.8}} > > Although the code runs without errors it doesnt return what i want . How > > am I wrong? Should i have to use next or break statement here or sth else? > > please help me.Thanks in advance >
It is not clear to me what your exact boundary conditions are for changing probabilities, or even what your real goal is, but maybe something like the following will get you started. Stage=1 is before there are greater than 2 'a's and 2 'b's. set.seed(3724) x <- character(0) p <- .5 stage <- 1 for(i in 1:20){ x <- c(x, sample(c('a','b'),1,prob=c(p,1-p))) suma <- sum(x=='a') sumb <- sum(x=='b') #check if first condition is met if(suma > 2 & sumb > 2) { #select a starting value for changed p value and do this only once if(stage == 1) {stage <- 2; if(suma >= sumb) p <-.8 else p <- .2} #check for excess of 'a's or 'b's if(suma - sumb > 2) p <- .2 if(sumb - suma > 2) p <- .8 } } If this doesn't do what you want, then write back to R-help describing what your ultimate goal is (i.e., what this method of randomization is supposed to accomplish), and someone may be able to give you better advice. Hope this is helpful, Dan Daniel Nordlund Bothell, WA USA ______________________________________________ R-help@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.