1
votes

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.

1
I believe you might be able to get it to plot if you use "zf1"Gregg H
Hi, I just changed the code a bit. Maybe that caused your nonconvergence? My R version is R-4.0.4. I tried again, but no problem with convergence.Ben Pelzer
Okay, that's nice!!! Where did you see that way of specifying dx for a factor? I googled quite a time but without finding this option for a factor. Thanks!Ben Pelzer
Actually, I don't really use this plot feature...but I've encountered this issue with factor and releveling in the past, so I thought I'd give it a go here.Gregg H

1 Answers

0
votes

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.