我正在拟合一个断棒模型,并想用它emtrends()
来拉出断点前后的斜率值。这里的代码是数据和分析的简化玩具版本。我不太清楚如何获得斜率 - 似乎在断点之前和之后得到相同的值。我究竟做错了什么?
library(ggplot2)
library(emmeans)
## toy data
df <- structure(list(Year = c(11, 11, 13, 13, 15, 15, 16, 16, 17,
17, 18, 18, 14, 14), YearFac = structure(c(1L, 1L, 2L, 2L,
4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 3L, 3L), .Label = c("11",
"13", "14", "15", "16", "17", "18"), class = "factor"), Class = c("A", "B", "A",
"B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B"), Mean = c(3.5, 3.7, 3.7, 4.2, 3.7,
4.5, 3.3, 4.9, 3.2, 5.8, 3.2, 6.3, NA, NA), YearPostTest = c(0, 0, 0,
0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 0)), row.names = c(3L, 4L, 5L, 7L, 8L,
10L, 11L, 13L, 14L, 16L, 17L, 19L, 20L, 21L), class = "data.frame")
# breakpoint model
mod <- lm(Mean ~ Year + YearPostTest + Year:Class +
YearPostTest:Class, data = df)
df$Pred <- predict(mod, newdata = df)
# plot data and predictions
ggplot(df) +
geom_point(aes(x = Year, y = Mean, colour = Class)) +
geom_line(aes(x = Year, y = Pred, colour = Class))
# make a new dataset with a few values - specifically, want to see slopes for A and for B
# classes before and after breakpoint
new <- data.frame(YearPostTest = c(0, 1, 0, 1),
Year = c(13, 18, 13, 18), Class = c("A", "A", "B", "B"))
emtrends(mod, ~Class|YearPostTest, var = "Year", data = new,
covnest = TRUE, cov.reduce = FALSE)