Last updated: 2026-01-23

Checks: 7 0

Knit directory: fiveMinuteStats/analysis/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(12345) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version b62b02b. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Untracked files:
    Untracked:  figure/
    Untracked:  temp.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/gibbs1.Rmd) and HTML (docs/gibbs1.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd b62b02b Peter Carbonetto 2026-01-23 wflow_publish("analysis/gibbs1.Rmd")
html f2164c5 Peter Carbonetto 2026-01-23 Build site.
Rmd 8dc27e5 Peter Carbonetto 2026-01-23 More updates to the gibbs1 vignette.
Rmd 76bd60d Peter Carbonetto 2026-01-23 Some updates to the gibbs1 vignette.
html 76bd60d Peter Carbonetto 2026-01-23 Some updates to the gibbs1 vignette.
html 5f62ee6 Matthew Stephens 2019-03-31 Build site.
Rmd 0cd28bd Matthew Stephens 2019-03-31 workflowr::wflow_publish(all = TRUE)
Rmd d5d3e06 Jasha 2018-05-07 Fix typo
html 34bcc51 John Blischak 2017-03-06 Build site.
Rmd 5fbc8b5 John Blischak 2017-03-06 Update workflowr project with wflow_update (version 0.4.0).
Rmd 391ba3c John Blischak 2017-03-06 Remove front and end matter of non-standard templates.
html 8e61683 Marcus Davy 2017-03-03 rendered html using wflow_build(all=TRUE)
Rmd d674141 Marcus Davy 2017-02-26 typos, refs
html c3b365a John Blischak 2017-01-02 Build site.
Rmd 67a8575 John Blischak 2017-01-02 Use external chunk to set knitr chunk options.
Rmd 5ec12c7 John Blischak 2017-01-02 Use session-info chunk.
Rmd 8466ce3 stephens999 2016-05-02 add gibbs sampling example

See here for a PDF version of this vignette.

Prerequisites

Be familiar with the concept of joint distribution and a conditional distribution. Ideally also with the concept of a Markov chain and its stationary distribution.

Overview

Gibbs sampling is a very useful way of simulating from distributions that are difficult to simulate from directly. However, in this introduction to the key concept, we will use a Gibbs sampler to simulate from a very simple distribution that could be simulated from in other ways.

Gibbs sampling

Suppose \(X\) and \(Y\) are two binary random variables with joint distribution \(\Pr(X = x, Y = y) = p_{X,Y}(x, y)\) given by the following table:

Y = 0 Y = 1
X = 0 0.60 0.10
X = 1 0.15 0.15

That is, for example, \(p_{X,Y}(0,0) = 0.6\).

The conditional distribution of \(X\) given any given value is easy to compute by the usual formula for conditional probability, \(\Pr(A \mid B) = \Pr(A \cap B)/\Pr(B)\). For example, \[ \Pr(X=0 \mid Y=0) = \Pr(X=0 \cap Y=0)/\Pr(Y=0) = 0.6/0.75 = 0.8, \] and so \[ \Pr(X=1 \mid Y=0) = 1 - 0.8 = 0.2. \] Similarly, \[ \Pr(X=0 \mid Y=1) = 0.1/0.25 = 0.4, \] and so \[ \Pr(X=1 \mid Y=1) = 0.6. \]

We can just as easily compute the conditional distribution of \(Y\) for any given value of \(X\): \[ \begin{aligned} \Pr(Y=0 \mid X=0) = 6/7 \\ \Pr(Y=1 \mid X=0) = 1/7 \\ \Pr(Y=0 \mid X=1) = 1/2 \\ \Pr(Y=1 \mid X=1) = 1/2 \end{aligned} \]

Question: Suppose we start at some value of \(X,Y\) and proceed to iterate the following steps:

  1. Simulate a new value of \(X\) from \(\Pr(X \mid Y=y)\), where \(y\) is the current value of \(Y\).

  2. Simulate a new value of \(Y\) from \(\Pr(Y \mid X=x)\), where \(x\) is the current value of \(X\) (that is, the value generated in Step 1.)

What happens? Let’s try it.

This function returns 1 with probability \(p\) and 0 with probability \(1-p\):

rbernoulli <- function (p)
  as.numeric(runif(1) < p)

This function samples from the conditional distribution of X given Y:

sample_XgivenY <- function(y) {
  if (y == 0)
    x <- rbernoulli(0.2)
  else
    x <- rbernoulli(0.6)
  return(x)
}

This function samples from the conditional distribution of Y given X:

sample_YgivenX <- function (x) {
  if (x == 0)
    y <- rbernoulli(1/7)
  else
    y <- rbernoulli(0.5)
  return(y)
}

Now let’s repeat Steps 1 and 2 one thousand times:

set.seed(100)
niter <- 1000
X <- rep(0,niter)
Y <- rep(0,niter)
X[1] <- 1
Y[1] <- 1
for (i in 2:niter) {
  X[i] <- sample_XgivenY(Y[i-1])
  Y[i] <- sample_YgivenX(X[i])
}
res <- data.frame(X = X,Y = Y)

Here is what happens for the first 20 iterations:

head(res,20)
#    X Y
# 1  1 1
# 2  1 1
# 3  1 1
# 4  1 1
# 5  0 0
# 6  0 0
# 7  0 0
# 8  0 0
# 9  0 0
# 10 0 0
# 11 0 0
# 12 0 0
# 13 0 0
# 14 0 0
# 15 0 0
# 16 0 0
# 17 0 0
# 18 0 0
# 19 0 0
# 20 1 0

And here is a summary of what proportion of the rows are of each type:

table(res)/niter
#    Y
# X       0     1
#   0 0.617 0.092
#   1 0.154 0.137

As you can see, the proportion of iterations in which \(X=x\) and \(Y=y\) is quite close to \(\Pr(X=x,Y=y) = p_{X,Y}(x,y)\). This is not a coincidence!

Explanation

What we have done here is simulate a Markov chain \[ (X_1,Y_1), (X_2,Y_2), (X_3,Y_3), \dots \] whose stationary distribution is \(\Pr(X=x,Y=y)=p_{X,Y}(x,y)\).

To see that the pairs \((X,Y)\) form a Markov chain, note that the simulation of \(X_i\) is done using only the previous value \(Y_{i-1}\), and the simulation of \(Y_i\) is done using only \(X_i\). So simulation of \((X_i,Y_i)\) depends on the previous states only through the immediate previous state \((X_{i-1},Y_{i-1})\), which means it is a Markov chain. (And in fact it only depends on \(Y_{i-1}\), but that is not so important.)

To see why it has stationary distribution \(p_{X,Y}(x,y)\), imagine simulating \(X_1, Y_1\) from this distribution, so \(\Pr(X_1=x,Y_1=y)= p_{X,Y}(x,y)\), and in particular \(\Pr(Y_1=y) = \sum_x p_{X,Y}(x,y) = p_Y(y)\).

Now, what is \(\Pr(X_2=x,Y_1=y)\)? Well we know \[ \Pr(X_2=x,Y_1=y) = \Pr(Y_1=y) \Pr(X_2=x \mid Y_1=y). \] And we know from above that \[ \Pr(Y_1=y) = p_{Y}(y). \] And we know that, given \(Y_1=y\), \(X_2\) was simulated from the conditional distribution \(p_{X|Y}(x \mid y)\), so \[ \Pr(X_2=x \mid Y_1=y) = p_{X|Y}(x \mid y). \] Putting these together, we have \[ \Pr(X_2=x,Y_1=y) = p_{Y}(y) p_{X|Y}(x \mid y) = p_{X,Y}(x,y). \]

Essentially the same argument shows that \(\Pr(X_2=x, Y_2=y) = p_{X,Y}(x,y)\). (This is left as an exercise.)

Thus, we have shown that if \(\Pr(X_1=x, Y_1=y) = p_{X,Y}(x,y)\), then also \(\Pr(X_2=x, Y_2=y) = p_{X,Y}(x,y)\). That is exactly what it means for \(p_{X,Y}(x,y)\) to be the “stationary distribution”: if we start the chain by simulating from that distribution, then it remains in that distribution after one step, and so it remains in that distribution forever.

Of course, we did not start the chain at that distribution. But the above argument shows that this is indeed the stationary distribution. There is a general result that discrete Markov chains “converge” to their stationary distribution provided that they “irreducible and aperiodic” (which this Markov chain is). That is, for large enough \(n\), we should see \(\Pr(X_n=x, Y_n=y) \approx p_{X,Y}(x,y)\) no matter where we start. Furthermore, in the long run, the proportion of iterations spent in each state will also converge to this distribution.

This explains the simulation result.


sessionInfo()
# R version 4.3.3 (2024-02-29)
# Platform: aarch64-apple-darwin20 (64-bit)
# Running under: macOS 15.7.1
# 
# Matrix products: default
# BLAS:   /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRblas.0.dylib 
# LAPACK: /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.11.0
# 
# locale:
# [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
# 
# time zone: America/Chicago
# tzcode source: internal
# 
# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods   base     
# 
# loaded via a namespace (and not attached):
#  [1] vctrs_0.6.5       cli_3.6.5         knitr_1.50        rlang_1.1.6      
#  [5] xfun_0.52         stringi_1.8.7     promises_1.3.3    jsonlite_2.0.0   
#  [9] workflowr_1.7.1   glue_1.8.0        rprojroot_2.0.4   git2r_0.33.0     
# [13] htmltools_0.5.8.1 httpuv_1.6.14     sass_0.4.10       rmarkdown_2.29   
# [17] evaluate_1.0.4    jquerylib_0.1.4   tibble_3.3.0      fastmap_1.2.0    
# [21] yaml_2.3.10       lifecycle_1.0.4   whisker_0.4.1     stringr_1.5.1    
# [25] compiler_4.3.3    fs_1.6.6          Rcpp_1.1.0        pkgconfig_2.0.3  
# [29] later_1.4.2       digest_0.6.37     R6_2.6.1          pillar_1.11.0    
# [33] magrittr_2.0.3    bslib_0.9.0       tools_4.3.3       cachem_1.1.0