[英]How do I to run GLM with interaction term and multiple non-interaction variables in R?
[英]Plotting glm interaction with 3 variables in R
我有以下具有分类变量相互作用的逻辑模型,希望在R中进行绘制。
model<- glm(df5$combined == "No" ~ df5$rs_glm5scale * df5$scenario, family="binomial")
方案变量具有两个类别(A和B)。
我尝试了以下方法,但不适用于y轴:
glmplot<-ggplot(model, aes(x= df5$rs_glm5scale, y= df5$combined == "No", group=df5$scenario))+geom_line(size=1, aes(color= df5$scenario))
我将如何在图表上绘制?
您可以创建一个数据网格来绘制:
library(tidyverse)
library(modelr)
model = glm(combined == "No" ~ rs_glm5scale * scenario, data = df5, family="binomial")
grid = df5 %>% data_grid(rs_glm5scale = seq_range(rs_glm5scale, 20), scenario)
grid$predictions = predict(model, newdata = grid, type = 'response')
grid %>% ggplot(aes(x = rs_glm5scale, y = predictions, color = scenario)) +
geom_line()
这是使用基数R的解决方案:
# First create a parameter grid to make predictions
grid <- expand.grid(
rs_glm5scale = seq(min(df5$rs_glm5scale), max(df5$rs_glm5scale), length.out = 1000),
scenario = c("A", "B")
)
# Then make predictions
pred <- predict(
model,
newdata = grid,
type = "response"
)
cond <- grid$scenario == "A" # to select predictions corresponding to scenario A
# Plot the predictions for category "A"
plot(grid$rs_glm5scale[cond], pred[cond], col = "darkgrey",
ylim = c(0, 1), type = "l", lwd = 2)
# Add a line for category "B"
lines(grid$rs_glm5scale[!cond], pred[!cond], col = "black", lwd = 2)
legend("bottomright", c("A", "B"), col = c("darkgrey", "lightgrey"), lwd = 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.