Last active
August 29, 2015 14:04
-
-
Save isaactpetersen/98e432adb48f49f767f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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