Skip to content

Instantly share code, notes, and snippets.

@wpetry
Last active April 9, 2018 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpetry/f6b125269a08dae909083ed8b9cf1266 to your computer and use it in GitHub Desktop.
Save wpetry/f6b125269a08dae909083ed8b9cf1266 to your computer and use it in GitHub Desktop.
Generate random compositions that sum to <=1
## Generate random compositions that sum to <=1
library(gtools)
library(ggtern)
library(scatterplot3d)
rCompos <- function(n, subsamples, alphas = NULL){
if(is.null(alphas)) alphas <- rep(1, subsamples)
sums <- matrix(runif(n), ncol = 1)
dirichlet <- gtools::rdirichlet(n, alphas)
output <- apply(dirichlet, 2, function(x) sums*x)
return(output)
}
## Generate test data:
mydata <- rCompos(n = 10000, subsamples = 3)
rowSums(mydata)
## Check evenness of sampling across sum component
hist(rowSums(mydata), 100)
## Check evenness of sampling across proportional component
ggtern(data = data.frame(mydata), aes(x=X1, y=X2, z=X3))+
geom_hex_tern()+
theme_bw()
## Check evenness of sampling in 3 dimensions
scatterplot3d::scatterplot3d(mydata)
scatterplot3d::scatterplot3d(mydata, angle = 180)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment