Skip to content

Instantly share code, notes, and snippets.

@clayford
Last active August 29, 2015 14:10
Show Gist options
  • Save clayford/7fc2257294aea10db5e6 to your computer and use it in GitHub Desktop.
Save clayford/7fc2257294aea10db5e6 to your computer and use it in GitHub Desktop.
function to simulate proportional sum of exponential variables
# function to simulate proportional sum of exponential variables
# p = p1,p2,p3,...,pn sum to one
# r = rates for exponential random variables
sumExp <- function(p,r){
if(sum(p) != 1) stop("p does not sum to 1")
if(length(p) != length(r)) stop("p and r not equal lengths")
x <- rexp(length(r),rate = r)
crossprod(p,x)
}
# Example
out <- replicate(n = 10000, expr = sumExp(p=c(0.1,0.2,0.3,0.4), r=c(0.5,1,1.5,3)))
hist(out, freq = F)
lines(density(out))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment