r - cplot R 因子 2 类别的边际效应
问题描述
R中的cplot函数确实不能处理具有两个级别的因子变量吗?我想为每个“年龄”值(1-10)绘制一个平均边际效应为“z”(0或1)的图。使用
cplot(model1, x="age", dx="z", what="效果")
工作正常,而
cplot(model2, x="age", dx="zf", what="效果")
导致错误消息。
# Simulate x and z data, uncorrelated.
age <- rep(c(1,2,3,4,5,6,7,8,9,10, 1,2,3,4,5,6,7,8,9,10),100)
z <- rep(c(0,0,0,0,0,0,0,0,0, 0, 1,1,1,1,1,1,1,1,1, 1),100)
zf <- factor(z)
library(margins)
set.seed(8352)
# Simulate data.
e <- rlogis(2000,0,1)
Y <- -12 + age + 11*z + e
y <- ifelse(Y > 0, 1, 0)
da <- data.frame(y,age,z,zf)
# Estimate equation with z as numeric variable.
model1 <- glm(y ~ age + z, family=binomial(link="logit"), da)
cplot(model1, x="age", dx="z", what="effect")
# Estimate equation with z as a factor.
model2 <- glm(y ~ age + zf, family=binomial(link="logit"), da)
cplot(model2, x="age", dx="zf", what="effect")
最终的 cplot 调用生成:
plot.window(...) 中的错误:需要有限的“xlim”值此外:警告消息:1:在 min(x) 中:min 没有非缺失参数;返回 Inf 2:在 max(x) 中:max 没有非缺失参数;返回 -Inf 3: In min(x) : min 没有非缺失参数;返回 Inf 4:在 max(x) 中:max 没有非缺失参数;返回-Inf
谢谢你的帮助,
本·佩尔泽。
解决方案
如果您对代码进行以下调整,则可以从因子 IV 中获得所需的图。
zg <- relevel(zf, ref=2)
da <- data.frame(y,age,z,zf,zg)
model3 <- glm(y ~ age + zg, family=binomial(link="logit"), da)
cplot(model3, x="age", dx="zg0", what="effect")
希望这会有所帮助。
推荐阅读
- flutter - 如何在 Flutter 中编码矩形+椭圆形状
- amazon-web-services - AWS Internet Gateway Id 是否始终以“igw-”开头,或者可能不同?
- android - 在 android studio 中使用驱动器 api 使文件可共享
- c# - 为什么我的 Console.WriteLine(); 不适用于引用的外部项目?
- tfs - 管道中的 yaml 任务可以读写历史数据吗?
- java - StringTokeniser 不读取数据
- php - 使用 ajax 如何在 ckeditor 中显示查询中的数据
- java - Graal 本机图像中缺少属性文件
- javascript - 如何将标题菜单项重新路由到 URL 而不是 React/Gatsby 中的内部文件?
- arrays - 我怎样才能更好地重构这段代码?