1

我有一个数据集,其中包含来自 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)
4

1 回答 1

1

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

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()
于 2020-08-20T17:00:42.050 回答