简体   繁体   中英

cplot R marginal effect of factor 2 categories

Is it true that the cplot function in R cannot deal with a factor variable, having two levels? I would like to make a plot with the average marginal effect of "z" (0 or 1) for each value of "age" (1-10). Using

cplot(model1, x="age", dx="z", what="effect")

works fine, whereas

cplot(model2, x="age", dx="zf", what="effect")

causes an error message.


# 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")

The final cplot call generates:

Error in plot.window(...): need finite 'xlim' values In addition: Warning messages: 1: In min(x): no non-missing arguments to min; returning Inf 2: In max(x): no non-missing arguments to max; returning -Inf 3: In min(x): no non-missing arguments to min; returning Inf 4: In max(x): no non-missing arguments to max; returning -Inf

Thanks for any help,

Ben Pelzer.

If you make the following adjustment to your code, you can get the desired plot from a factor 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")

Hope this is helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM