如何向混合模型添加偏移量

How to add an offset to mixed model

我有一个数据集,其中包含来自 4 周试验的奶牛的步数,其中每只动物在第 2 周开始时接受处理 A 或处理 B,我想知道这两种方法的步数如何与第 1 周相比,治疗组每周都会发生变化。

如何为我的模型添加偏移量来执行此操作?

我运行加偏移量前的模型是这样的:

mod.1 <- glmmTMB(Step.count ~ Week*Treatment + (1|Cow.ID), data = data.df, family = poisson) 

这是我的数据示例

data.1 <- data.frame(Cow.ID = rep(1, 20),
       Week = sample(c(1,2,3,4), 20, replace = TRUE),
       Treatment = sample(c("infected"), 20, replace = TRUE),
       Step.count = rpois(20, 60.1))

data.2 <- data.frame(Cow.ID = rep(2, 20),
                 Week = sample(c(1,2,3,4), 20, replace = TRUE),
                 Treatment = sample(c("infected"), 20, replace = TRUE),
                 Step.count = rpois(20, 60.1))

data.3 <- data.frame(Cow.ID = rep(3, 20),
                 Week = sample(c(1,2,3,4), 20, replace = TRUE),
                 Treatment = sample(c("non-infected"), 20, replace = TRUE),
                 Step.count = rpois(20, 60.1))


data.4 <- data.frame(Cow.ID = rep(4, 20),
                 Week = sample(c(1,2,3,4), 20, replace = TRUE),
                 Treatment = sample(c("non-infected"), 20, replace = TRUE),
                 Step.count = rpois(20, 60.1))


sample.df <- rbind(data.1, data.2, data.3, data.4)

如果没有您的数据示例很难说,但假设您有这样的数据名

library(dplyr)

cows <- tibble(
    Cow.Id = rep(1:4, times = 5),
    Week = rep(1:5, each = 4),
    Step.count = floor(runif(20, 100,200)),
    Treatment = rep(c('A','B','A','B'), times = 5),
)

然后,你可以很容易地计算出每头牛的一列 Step.count.offset 是这样的:

cows.clean <- cows %>%
    group_by(Cow.Id) %>%
    arrange(Week) %>%
    mutate(
        Step.count.offset = Step.count - first(Step.count)
    ) %>%
    ungroup()