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.