user3910465
user3910465

Reputation: 1

Random number sequence generator in R with advanced criteria

I'm looking to generate a random number sequence with 14 numbers between 1 & 25 (inclusive). Which I can do in R using > sample (1:25, 14). However, for some of the sequences I need certain numbers excluded (2,3,4,5,6,16,21,etc.). I also need to make sure certain numbers don't fall within the first 4 numbers of the sequences (i.e.1-6, 16, 21,etc.) I also need certain sequences where certain numbers appear twice between the 5th and 14th position.

Sorry if it's not clear, but I basically need a random number sequence generator in R which

If anyone knows of function that could do this I'd be very grateful.

Upvotes: 0

Views: 1190

Answers (1)

bjoseph
bjoseph

Reputation: 2166

This function does what you want:

specialSample <- function(yourSample, sampleTimes, exclusion, firstFour, appearTwice){
excludedSample <- yourSample[!yourSample%in%exclusion]
first <- sample(excludedSample,1,prob=excludedSample%in%firstFour)
firstposition <- sample(1:4,1)
second <- sample(excludedSample,1,prob=excludedSample%in%appearTwice)
twice <- c(second,second)
sampler <- sample(excludedSample,sampleTimes-length(exclude),replace=TRUE)
positions <- sample(5:14,2)
result <- sampler
result[firstposition] <- first
result[positions] <- twice
return(result)
}

The arguments are

yourSample is the sequence you are sampling form

sampleTimes is how many values you want in your sample (I have specified replace=TRUE if you want replace=FALSE then length(sampleTimes) must be < length(yourSample)

exclusion is the numbers you want excluded

firstFour numbers that you want one of to be in the first four

appearTwice numbers you want to appear twice in certain random positions

 > numbers <- 1:25
 > exclude <- c(2,4,8)
 > firstFour <- 1:4
 > appearTwice <- c(11,12)

 > test <- specialSample(numbers,25,exclude,firstFour,appearTwice)
!> test
  [1] 12 23  3  9 10 10 21 12  7 17 24 15 22 12  3 14  9  9  1  6 19 15

The basic idea is to exploit indexing of vectors vec[positionN]<-value and probability of sampling to get the values you want in the places you want.

Upvotes: 3

Related Questions