首页 > 解决方案 > 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

谢谢你的帮助,

本·佩尔泽。

标签: r

解决方案


如果您对代码进行以下调整,则可以从因子 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")

希望这会有所帮助。


推荐阅读