#' Draw values from a beta distribution and plot the probability density
#' function
#'
#' @param n number of observations to draw
#' @param a non-negative alpha parameter of the beta distribution
#' @param b non-negative beta parameter of the beta distribution
#'
#' @details The Beta distribution with parameters \eqn{a} and \eqn{b} has
#' density:
#'
#' \deqn{
#' \Gamma(a+b)/(\Gamma(a)\Gamma(b))x^(a-1)(1-x)^(b-1)
#' }
#'
#' for \eqn{a > 0}, \eqn{b > 0} and \eqn{0 \le x \le 1}.
#'
#' @examples
#' # Draw from beta distribution with parameters a = 1 and b = 3
#' beta_plot(a = 1, b = 3)
#'
#' @seealso \code{\link{rbeta}}, \code{\link{geom_density}}
#' @import ggplot2
#' @importFrom stats rbeta
#' @export
beta_plot <- function(n = 10000, a = 1, b = 3) {
x <- NULL
# ensure non-zero/negative argument values
if (any(n <= 0, a <= 0, b <= 0))
stop("n, a, and b arguments must be greater than 0.", call. = FALSE)
# draw distributions
sims <- rbeta(n = n, shape1 = a, shape2 = b)
# convert to data frame for ggplot2 compatability
sims <- data.frame(x = sims)
# plot probability density function
ggplot(sims, aes(x)) +
geom_density() +
xlab("") + ylab("Probability Density Function") +
theme_bw()
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.