Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save florianhartig/8433880 to your computer and use it in GitHub Desktop.
Save florianhartig/8433880 to your computer and use it in GitHub Desktop.
Distributes n=3 plant species across k=12 x m=12 grid cells, in a way that no individual has another individual of it’s own species in its 4-cell (von Neumann: up, down, left, right) neighborhood. This script originated from a question posted on http://theoreticalecology.wordpress.com/2014/01/14/sampling-design-combinatorics/ , solution posted b…
# plot layout
x=12
y=12
# number of diff samples
n=3
# plot A, which holds
A=array(NA,c(x,y))
# repeat 1 through n as many times as subplots are in A
s=rep(1:n, x*y/n)
# stop after kmax iterations in the while loop
kmax=10000
# loop over supplots in A
for (i in 1:x) {
for (j in 1:y) {
# if a suitable subplot was found
found=FALSE
# number of remaining suplots
ns=length(s)
# counter to break possible infinite while loop
k=0
while (!found) {
k=k+1
if (k>kmax) break
# choose a sample from remaining subplots
A[i,j] = sample(s,1)
# assume it suits
found=TRUE
# if it doesn’t reset
if (i>1 && A[i,j] == A[i-1,j]) found=FALSE
if (j>1 && A[i,j] == A[i,j-1]) found=FALSE
}
# warn if equal subplots are next to each other
if (found==FALSE) warning("*** layout not possible, ran out of possible subplots! ***")
# break if the last subplot is gone
if (length(s)==1) break
# first remove all equal subplots,
s=s[! s %in% A[i,j]]
# the append one less to the remaining subplots
s=append(s,rep(A[i,j],ns-length(s)-1))
}
}
# text and image output
print(A)
for (i in 1:n) print(paste(i, ": ", length(A[A==i]),sep=""))
image(A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment