-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.25.R
50 lines (44 loc) · 921 Bytes
/
3.25.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
## ---- Gibbs ----
## Packages
library(ggplot2)
library(gridExtra)
## Parameters
n <- 20
alpha <- 0.5
beta <- 0.5
N <- 1e4
## Target Distribution
ptd <- function(n, x, y, alpha, beta) {
out <-
choose(n, x) * y ^ (x + alpha - 1) *
(1 - y) ^ (n - x + beta - 1)
out
}
## Gibbs Sampling
x <- 0
y <- rbeta(n = 1, shape1 = alpha, shape2 = beta)
X <- c(x)
Y <- c(y)
avg_Y <- c(mean(Y))
for (i in 1:N) {
x <- rbinom(n = 1, size = n, prob = y)
X <- c(X, x)
y <- rbeta(n = 1,
shape1 = x + alpha,
shape2 = n - x + beta)
Y <- c(Y, y)
avg_Y <- c(avg_Y, mean(Y))
}
## Histogram
data <- data.frame(X, Y)
p1 <-
ggplot(data = data, mapping = aes(x = Y)) +
geom_histogram(binwidth = 0.01)
## Density of Beta(alpha,beta)
seq_x <- seq(0, 1, length = 100)
p2 <- qplot(
x = seq_x,
y = dbeta(seq_x, shape1 = alpha, shape2 = beta),
geom = "line"
)
grid.arrange(p1, p2, nrow = 2)