Skip to content

Instantly share code, notes, and snippets.

@lzachmann
lzachmann / class-sim-utils.R
Last active February 16, 2022 18:44
Validating results of `dinterval` and `dcat`, a work in progress
# Moment match for the beta distribution.
params_from_moments <- function(mu, sigma) {
alpha <- (mu^2 - mu^3 - mu * sigma^2) / sigma^2
beta <- (mu - 2 * mu^2 + mu^3 - sigma^2 + mu * sigma^2) / sigma^2
c(alpha = alpha, beta = beta)
}
moments_from_params <- function(alpha, beta) {
mu <- alpha / (alpha + beta)
sigma <- sqrt((alpha * beta) / ((alpha + beta)^2 * (alpha + beta + 1)))
c(mu = mu, sigma = sigma)
@lzachmann
lzachmann / correlated-effects-greta.R
Created July 7, 2020 20:17
Separating fixed and random components in a correlated effects model
library(tidyverse)
library(greta)
library(mvtnorm)
library(bayesplot)
# ---- set up ----
J <- 40 # number of groups
n_j <- sample.int(15, J, replace = TRUE) # number of observations per group
@lzachmann
lzachmann / arbitrary-pixel-time-series-ndvi.csv
Created February 20, 2018 18:18
A hierarchical model for inference on phenology
img_date centered_doy ndvi_flt year_index centered_decade
2000-02-18 -133.5 0.1774 1 -0.851
2000-03-05 -117.5 0.2836 1 -0.851
2000-03-21 -101.5 0.27 1 -0.851
2000-04-22 -69.5 0.3241 1 -0.851
2000-05-08 -53.5 0.585 1 -0.851
2000-05-24 -37.5 0.7536 1 -0.851
2000-06-09 -21.5 0.8622 1 -0.851
2000-06-25 -5.5 0.8507 1 -0.851
2000-07-11 10.5 0.862 1 -0.851
@lzachmann
lzachmann / coef-intuititions.r
Created February 15, 2018 22:46
Making sense of parameter estimates tied to models of Mojave Desert Tortoise survival
library(tidyverse)
plus_minus <- function(x, scalar) c(x-scalar, x, x+scalar)
scenarios <- expand.grid(
b0 = 2.86 %>% plus_minus(1), # intercept
b1 = -.28 %>% plus_minus(.5) # the effect of translocation
) %>% mutate(scenario = 1:n())
@lzachmann
lzachmann / biv_dist_plot.r
Last active January 13, 2017 21:48
Modeling multivariate outcomes
biv_dist_plot <- function(df, x=NULL, y=NULL, bins=50) {
library(ggplot2)
library(gridExtra)
h_top <- ggplot(data=df, aes_string(x=x)) +
geom_histogram(aes(y=..density..), fill = "white", color = "black", bins=bins) +
stat_density(colour = "blue", geom="line", size = 1, position="identity",
show.legend=FALSE) +
theme(axis.title.x = element_blank())
@lzachmann
lzachmann / full_pois.stan
Created November 4, 2016 16:42
Modeling spatially correlated outcomes at multiple sites
data {
int<lower = 1> n;
int<lower = 1> p;
matrix[n, p] X;
int<lower = 0> y[n];
int<lower = 1> m;
int<lower = 1, upper = n> n_each[m];
int<lower = 1, upper = n> idx[m, 2]; // start and stop indices for plots
matrix<lower = 0>[n, n] D;
}