The “stan_glm” Function in R
Package: rstanarm
Purpose: Fits a generalized linear model (GLM) using Stan.
General class: Statistical modeling
Required argument(s):
formula: A symbolic description of the model to be fit.
data: The data frame containing the variables in the model.
Notable optional arguments:
family: The distributional family and link function to use. The default is Gaussian with an identity link.
prior: Prior specification for the coefficients. Default is a weakly informative normal prior.
...: Additional arguments controlling the fitting process.
Example:
# Load the rstanarm package
library(rstanarm)
# Fit a GLM for binary outcome
data <- data.frame(
y = c(1, 0, 1, 0, 1),
x1 = c(1, 0, 3, 0, 5),
x2 = c(0, 5, 1, 5, 2)
)
model <- stan_glm(y ~ x1 + x2, data = data, family = binomial(link = "logit"))
# Summary of the fitted model
summary(model)
# Create predictive intervals for new data that are likely to result in a value of 1
new_data = data.frame(x1 = 6:8, x2 = 1:3)
predictive_interval(model, newdata = new_data, prob = 0.5)This example demonstrates how to use the stan_glm function from the rstanarm package to fit a generalized linear model (GLM) for the binary outcome (y) based on predictors (x1 and x2) in the data frame data. Optional arguments like family can be specified for different distributions, and additional control over the fitting process can be achieved with prior and other arguments.