knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "# ",
  fig.path = "figures/README-",
  dpi = 250
)

dirichlet

dirichlet implements the (d/r) statistics functions for the Dirichlet distribution in R. It is ideal for using in other packages since it is light weight.

Getting dirichlet

dirichlet is not yet on CRAN, so to get it use the following:

# install.packages("devtools")
devtools::install_github("dkahle/dirichlet")

The ddirichlet() function

The PDF (the f(x)) can be evaluated with the ddirichlet() function:

library(dirichlet)
ddirichlet(c(.5,.5), c(.5, .5))

You can visualize it in barycentric coordinates like this:

library(dplyr, warn.conflicts = FALSE)
library(ggplot2); theme_set(theme_bw())
f <- function(v) ddirichlet(v, c(20, 10, 5))
mesh <- simplex_mesh(.0025) %>% as.data.frame %>% tbl_df
mesh$f <- mesh %>% apply(1, function(v) f(bary2simp(v)))

(p <- ggplot(mesh, aes(x, y)) +
  geom_raster(aes(fill = f)) +
  coord_equal(xlim = c(0,1), ylim = c(0, .85)))

The rdirichlet() function

Random number generation can be performed with rdirichlet():

set.seed(1)
rdirichlet(5, c(1, 1, 1))  # rows sum to 1
rowSums(rdirichlet(3, c(1, 1, 1)))

You can visualize these points on top of the distribution above like this:

points <- rdirichlet(250, c(20, 10, 5)) %>% simp2bary %>% 
  as.data.frame %>% tbl_df %>% rename(x = V1, y = V2)

p + geom_point(data = points, color = "orange", alpha = .3)


dkahle/dirichlet documentation built on June 4, 2023, 4:51 a.m.