基于R语言的多变量预测glm可视化
我想使用以下数据集来拟合glm并可视化predict() 然后使用基于R语言的多变量预测glm可视化,r,glm,predict,R,Glm,Predict,我想使用以下数据集来拟合glm并可视化predict() 然后使用myglm预测new.y: new.y = predict(myglm, newdata=new.x, se.fit=TRUE) 将新的.x和新的.y组合起来: addThese <- data.frame(new.x, new.y) 我仍然想知道这是否是创建新.data的正确方法,但我会尝试一下。因此,对于您的数据,稍微修改一下您的代码: myglm <- glm(y ~ x1 + x2 + x3 + x1:x2
myglm
预测new.y
:
new.y = predict(myglm, newdata=new.x, se.fit=TRUE)
将新的.x和新的.y组合起来:
addThese <- data.frame(new.x, new.y)
我仍然想知道这是否是创建
新.data
的正确方法,但我会尝试一下。因此,对于您的数据,稍微修改一下您的代码:
myglm <- glm(y ~ x1 + x2 + x3 + x1:x2, family = gaussian, data = mydata)
minx <- min(mydata$x1)
maxx <- max(mydata$x1)
# create data with all combinations of x1, x2, x3
new.data <- expand.grid(x1 = seq(minx, maxx, length.out = 60),
x2 = unique(mydata$x2),
x3 = unique(mydata$x3)
)
# visualize data
data.frame(predict(myglm, newdata = new.data, se.fit = T)[1:2]) %>%
bind_cols(new.data) %>%
mutate(d15N = exp(fit), lwr = fit - 1.96 * se.fit, upr = fit + 1.96 * se.fit) %>%
ggplot(aes(x = x1, y = fit, colour = interaction(x2, x3))) +
geom_point(size = 1, alpha = .75, pch = 19, position = "jitter") +
geom_smooth(aes(ymin = lwr, ymax = upr), stat = "identity", alpha = .5) +
facet_wrap(~interaction(x2, x3, sep = " : "), nrow = 5) +
ggthemes::theme_few() +
labs(y = "Predicted value", x = bquote(x[1])) +
theme(legend.position = "none")
myglm您想在new.x
中使用与mydata
中相同的x2
和x3
吗?@ANG,是的,我想在mydata
中保持因子x2
和x3
与mydata$x2
相同。因此,在创建new.x
时,只需使用x2=mydata$x2
和x3=mydata$x3
,亲爱的乌图邦,请检查并编辑答案,是lwr=fit-1.96*se.fit
,应该是lwr=exp>(fit-1.96*se.fit)
?与upr
相同。非常感谢!
new.x <- data.frame(
x1=seq(min, max, length=60),
x2= ???
x3= ???)
new.y = predict(myglm, newdata=new.x, se.fit=TRUE)
addThese <- data.frame(new.x, new.y)
addThese <- mutate(addThese,
d15N=exp(fit),
lwr=exp(fit-1.96*se.fit),
upr=exp(fit+1.96*se.fit))
ggplot(addThese, aes(x1, fit))+
geom_point(shape=21, size=3)+
geom_smooth(data=addThese,
aes(ymin=lwr, ymax=upr),
stat='identity')
myglm <- glm(y ~ x1 + x2 + x3 + x1:x2, family = gaussian, data = mydata)
minx <- min(mydata$x1)
maxx <- max(mydata$x1)
# create data with all combinations of x1, x2, x3
new.data <- expand.grid(x1 = seq(minx, maxx, length.out = 60),
x2 = unique(mydata$x2),
x3 = unique(mydata$x3)
)
# visualize data
data.frame(predict(myglm, newdata = new.data, se.fit = T)[1:2]) %>%
bind_cols(new.data) %>%
mutate(d15N = exp(fit), lwr = fit - 1.96 * se.fit, upr = fit + 1.96 * se.fit) %>%
ggplot(aes(x = x1, y = fit, colour = interaction(x2, x3))) +
geom_point(size = 1, alpha = .75, pch = 19, position = "jitter") +
geom_smooth(aes(ymin = lwr, ymax = upr), stat = "identity", alpha = .5) +
facet_wrap(~interaction(x2, x3, sep = " : "), nrow = 5) +
ggthemes::theme_few() +
labs(y = "Predicted value", x = bquote(x[1])) +
theme(legend.position = "none")