7.4 Implementing the Metropolis-Hastings
<- function(N, w){
mh_tour # 1. Start the chain at location 3
<- 3
current
# 2. Initialize the simulation
<- rep(0, N)
mu
# 3. Simulate N Markov chain stops
for(i in 1:N){
# Simulate one iteration
<- one_mh_iteration(w = w, current = current)
sim
# Record next location
<- sim$next_stop
mu[i]
# Reset the current location
<- sim$next_stop
current
}
# 4. Return the chain locations
return(data.frame(iteration = c(1:N), mu))
}
library(ggplot2)
set.seed(84735)
<- mh_tour(N = 5000, w = 1)
mh_simulation_1 ggplot(mh_simulation_1, aes(x = iteration, y = mu)) +
geom_line()
ggplot(mh_simulation_1, aes(x = mu)) +
geom_histogram(aes(y = ..density..), color = "white", bins = 20) +
stat_function(fun = dnorm, args = list(4,0.6), color = "blue")
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Tuning the Metropolis-Hastings algorithm