# STATS 4CI3 January 30, 2019 # Generate from a mixture of Normals rmixnorm <- function(n, p, mu, s) { # p is the vector of mixing proportions # mu is the vector of means # s is the vector of standard deviations K <- length(p) # I will use explicit recycling here if (length(mu)!=K){ if (length(mu)>k) { warning(paste("Only first ",K, " means used.", sep="")) mu <- mu[1:k] } else { if (length(mu)%%K>0) warning("Length of p is not a multiple of length of mu") mu <- rep(mu, length=K) } } if (length(s)!=K){ if (length(s)>k) { warning(paste("Only first ",K, " sds used.", sep="")) s <- s[1:k] } else { if (length(s)%%K!=0) warning("Length of p is not a multiple of length of s") s <- rep(s, length=K) } } Z <- sample(K, n, prob=p, replace=T) rnorm(n, mu[Z], s[Z]) }