Skip to content

Instantly share code, notes, and snippets.

@stonegold546
stonegold546 / 1. ordered_example.R
Last active May 5, 2021 16:56
Polychoric correlations with Stan (accounts for missingness)
library(lavaan)
library(rstan)
library(cmdstanr)
set_cmdstan_path("~/cmdstan/")
source("create_poly_stan_missing.R")
HS9 <- HolzingerSwineford1939[, paste0("x", 1:9)]
# Pearson correlations
@stonegold546
stonegold546 / cens_pred.R
Last active October 17, 2023 15:02
Stan example with left-censored predictor at 0
library(rstan)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
# Simulate an example
set.seed(1234)
hist(x_true <- rt(2e2, 3) * 1.5)
# Create outcome
hist(y <- scale(rnorm(length(x_true), -.075 * x_true))[, 1])
@stonegold546
stonegold546 / count_gamma_reg.stan
Created March 21, 2022 18:54
Gamma-count dist
functions {
int sum0(vector x) {
int len = num_elements(x);
int res = 0;
for (i in 1:len) if (x[i] == 0) res += 1;
return res;
}
}
data {
int N;
@stonegold546
stonegold546 / 0_efa_example.R
Last active April 11, 2022 22:37
EFA example based off Rick Farouni's example on Holzinger-Swineford data
library(rstan)
library(lavaan)
cmdstanr::set_cmdstan_path("~/cmdstan/")
# https://rfarouni.github.io/assets/projects/BayesianFactorAnalysis/BayesianFactorAnalysis.html
# L is N_items BY N_factor loading matrix, constrained lower-triangular
# Cov = LL' + diag(res_vars), factors constrained orthogonal
# Chose items 3, 6 and 8 as markers of factors 1, 2 and 3
@stonegold546
stonegold546 / pair_13_asz.R
Last active May 20, 2022 20:34
trivial effect plot
library(data.table)
library(ggplot2)
library(scales)
set.seed(12345)
post_df <- data.table(
est = rnorm(13 * 12 / 2, 0, .05),
se = rlnorm(13 * 12 / 2, log(.09), log(.20 / .09) / qnorm(.9999))
)
post_df[, lo := qnorm(.025, est, se)]
@stonegold546
stonegold546 / generic_reg_ord_brms.R
Last active May 24, 2022 20:33
Continuous data ordinal regression using monotonic splines to estimate thresholds
### Block 02 -- Load packages
library(ordinalCont) # Just to check frequentist
library(splines2)
library(brms)
### Block 03 -- Load helper functions
source("helper_file_ord_generic.R")