Skip to content

Instantly share code, notes, and snippets.

@kgturner
Last active March 30, 2018 21:59
Show Gist options
  • Save kgturner/ce6637e4dc916fa338d04c88c234117d to your computer and use it in GitHub Desktop.
Save kgturner/ce6637e4dc916fa338d04c88c234117d to your computer and use it in GitHub Desktop.
Generate list of vectors with limited overlap. Useful for randomly assigning individuals from a pool to subsets (such as experimental blocks) with limited similarity between subsets..
#generate random number sets with limited overlap
#3/28/2018
#with em-bellis
####generate random integers from a pool####
#from 1-60, sample 10
sample.int(60, 10)
#[1] 34 42 45 54 3 5 20 25 53 40
#such as IDs of populations or individuals from a list
#pairwise comparisons
set1 <- sample.int(60,10)
set2 <- sample.int(60,10)
set1 %in% set3
#comparison gives logical vector
#[1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
####function to check matching/add to list####
#first make list containing starter set
plist <- list(set1=set1)
#defaults generate set of 10 IDs from a pool of 60 possible IDs with an overlap between any two sets of 4 or less
generate_set <- function(setList, pool=60, size=10, overlap=4) {
testset <- sample.int(pool,size)
for(i in 1:length(setList)) {
n <- testset %in% setList[[i]]
if (sum(n, na.rm=TRUE)>overlap) {
fail <- TRUE
}
}
if (fail==FALSE) {return(testplot)}
}
####while loop to run enough times to generate the required number of set assignments####
#here, produces list of 20 sets
while (length(plist) < 20) {
fail <- FALSE
plist <- c(plist, list(generate_plot(plist)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment