如何在JAGS回归模型中拟合有和没有交互的模型

时间:2018-02-22 17:30:32

标签: r bayesian jags r2jags

我正在使用this tutorial来围绕JAGS代码。在'具有附加分类预测器的相同模型'部分中,它指出“此模型包括性别和体长之间的相互作用”。如何删除它以便没有交互?

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

首先是数据:

Spaces

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)))

初始值并运行:

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)
}

1 个答案:

答案 0 :(得分:1)

交互项包含在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)
}