Skip to content

Instantly share code, notes, and snippets.

@isaactpetersen
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save isaactpetersen/98e432adb48f49f767f5 to your computer and use it in GitHub Desktop.

Select an option

Save isaactpetersen/98e432adb48f49f767f5 to your computer and use it in GitHub Desktop.
simulateIntegers <- function(n, sum, sd, pos.only = TRUE){
if(sum == 0 & pos.only == TRUE){
vec <- rep(0, n)
} else{
vec <- rnorm(n, sum/n, sd)
if (abs(sum(vec)) < 0.01) vec <- vec + 1
vec <- round(vec / sum(vec) * sum)
deviation <- sum - sum(vec)
for (. in seq_len(abs(deviation))){
vec[i] <- vec[i <- sample(n, 1)] + sign(deviation)
}
if (pos.only) while (any(vec < 0)){
negs <- vec < 0
pos <- vec > 0
vec[negs][i] <- vec[negs][i <- sample(sum(negs), 1)] + 1
vec[pos][i] <- vec[pos ][i <- sample(sum(pos ), 1)] - 1
}
}
vec
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment