library(magrittr)
compute_posterior_water_grid <- function(n = 20,
n_water = 6,
n_land = 3,
prior = rep(x = 1,times = n),
p_grid = seq(from = 0,
to = 1, length.out = n)){
# define posterior
# p_grid <- seq(from = 0, to = 1, length.out = n)
# compute likelihood at each value in grid
message("printing p_grid")
print(p_grid)
message("printing prior")
print(prior)
likelihood <- dbinom(x = n_water, size = n_water + n_land, prob = p_grid)
# compute product of likelihood and prior
unstd_posterior <- likelihood * prior
# standardize the posterior, so it sums to 1
posterior <- unstd_posterior / sum(unstd_posterior)
tibble::tibble(grid = p_grid, post = posterior)
}
base_plot_posterior_water_grid <- function(data){
with(data,
plot(grid,
post,
type = "b",
xlab = "Probability of Water",
ylab = "Posterior probability"))
mtext(paste0(nrow(data), " points"))
}
water_three <- compute_posterior_water_grid(n_water = 3,
n_land = 0)
#> printing p_grid
#> [1] 0.00000000 0.05263158 0.10526316 0.15789474 0.21052632 0.26315789
#> [7] 0.31578947 0.36842105 0.42105263 0.47368421 0.52631579 0.57894737
#> [13] 0.63157895 0.68421053 0.73684211 0.78947368 0.84210526 0.89473684
#> [19] 0.94736842 1.00000000
#> printing prior
#> [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
base_plot_posterior_water_grid(water_three)
compute_posterior_water_grid(n_water = 3,
n_land = 1) %>%
base_plot_posterior_water_grid()
#> printing p_grid
#> [1] 0.00000000 0.05263158 0.10526316 0.15789474 0.21052632 0.26315789
#> [7] 0.31578947 0.36842105 0.42105263 0.47368421 0.52631579 0.57894737
#> [13] 0.63157895 0.68421053 0.73684211 0.78947368 0.84210526 0.89473684
#> [19] 0.94736842 1.00000000
#> printing prior
#> [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
compute_posterior_water_grid(n_water = 5,
n_land = 2) %>%
base_plot_posterior_water_grid()
#> printing p_grid
#> [1] 0.00000000 0.05263158 0.10526316 0.15789474 0.21052632 0.26315789
#> [7] 0.31578947 0.36842105 0.42105263 0.47368421 0.52631579 0.57894737
#> [13] 0.63157895 0.68421053 0.73684211 0.78947368 0.84210526 0.89473684
#> [19] 0.94736842 1.00000000
#> printing prior
#> [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
####
# changing the prior to be 0 when below 0.5, and 1 otherwise
compute_posterior_water_grid(prior = ifelse(p_grid < 0.5, 0, 1),
n_water = 3,
n_land = 1)
#> printing p_grid
#> [1] 0.00000000 0.05263158 0.10526316 0.15789474 0.21052632 0.26315789
#> [7] 0.31578947 0.36842105 0.42105263 0.47368421 0.52631579 0.57894737
#> [13] 0.63157895 0.68421053 0.73684211 0.78947368 0.84210526 0.89473684
#> [19] 0.94736842 1.00000000
#> printing prior
#> Error in ifelse(p_grid < 0.5, 0, 1): object 'p_grid' not found
# but this doesn't work?!?!
Created on 2020-10-12 by the reprex package (v0.3.0)
hmmm, random thought, can I pass
...
and use those instead? It would require a bit of control statements to determine if the dots are set and to update the objects.