如何在 JAGS 回归模型中使用和不使用交互来拟合模型

How to fit a model with and without an interaction in a JAGS regression model

我正在使用 this tutorial 来研究 JAGS 代码。在 'Same model with an additional categorical predictor' 部分中指出 "This model includes an interaction between sex and body length"。我怎样才能删除它以便没有交互?

这是 R 和 JAGS 中的完整设置和模型。

首先是数据:

set.seed(42)

samplesize <- 50 # Larger sample size because we're fitting a more complex model
b_length <- sort(rnorm(samplesize)) # Body length
sex <- sample(c(0, 1), size = samplesize, replace = T) # Sex (0: female, 1: male)

int_true_f <- 30 # Intercept of females
int_true_m_diff <- 5 # Difference between intercepts of males and females
slope_true_f <- 10 # Slope of females
slope_true_m_diff <- -3 # Difference between slopes of males and females

mu <- int_true_f + sex * int_true_m_diff + (slope_true_f + sex * slope_true_m_diff) * b_length # True means
sigma <- 5 # True standard deviation of normal distributions

b_mass <- rnorm(samplesize, mean = mu, sd = sigma) # Body mass (response variable)

# Combine into a data frame:
snakes2 <- data.frame(b_length = b_length, b_mass = b_mass, sex = sex)
head(snakes2)

jagsdata_s2 <- with(snakes2, list(b_mass = b_mass, b_length = b_length, sex = sex, N = length(b_mass)))

JAGS 代码:

lm2_jags <- function(){
    # Likelihood:
    for (i in 1:N){
        b_mass[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance)
        mu[i] <- alpha[1] + sex[i] * alpha[2] + (beta[1] + beta[2] * sex[i]) * b_length[i]
    }
    # Priors:
    for (i in 1:2){
        alpha[i] ~ dnorm(0, 0.01)
        beta[i] ~ dnorm(0, 0.01)
    }
    sigma ~ dunif(0, 100)
    tau <- 1 / (sigma * sigma)
}

初始值和运行:

init_values <- function(){
    list(alpha = rnorm(2), beta = rnorm(2), sigma = runif(1))
}

params <- c("alpha", "beta", "sigma")

fit_lm2 <- jags(data = jagsdata_s2, inits = init_values, parameters.to.save = params, model.file = lm2_jags,
               n.chains = 3, n.iter = 12000, n.burnin = 2000, n.thin = 10, DIC = F)

相互作用项包含在您计算的 mu 中。性别通过斜率项改变了体长和体重之间公式的定义方式。要建立一个模型,将性别和身长视为独立于它们如何影响体重,您可以这样做:

mu <- int_true_f + (sex * int_true_m_diff) + b_length 

JAGS 代码将变为

lm2_jags <- function(){
  # Likelihood:
  for (i in 1:N){
    b_mass[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance)
    mu[i] <- alpha[1] + (sex[i] * alpha[2]) + (b_length[i] * alpha[3])
  }
  # Priors:
  for (i in 1:3){
    alpha[i] ~ dnorm(0, 0.01)
  }
  sigma ~ dunif(0, 100)
  tau <- 1 / (sigma * sigma)
}