0

I want to observe the effect of a treatment variable on my outcome Y. I did a multiple regression: fit <- lm (Y ~ x1 + x2 + x3). x1 is the treatment variable and x2, x3 are the control variables. I used the predict function holding x2 and x3 to their means. I plotted this predict function.

Now I would like to add a line to my plot similar to a simple regression abline but I do not know how to do this.

I think I have to use line(x,y) where y = predict and x is a sequence of values for my variable x1. But R tells me the lengths of y and x differ.

Prradep
  • 5,506
  • 5
  • 43
  • 84
diane
  • 1
  • 1

1 Answers1

2

I think you are looking for termplot:

## simulate some data
set.seed(0)
x1 <- runif(100)
x2 <- runif(100)
x3 <- runif(100)
y <- cbind(1,x1,x2,x3) %*% runif(4) + rnorm(100, sd = 0.1)

## fit a model
fit <- lm(y ~ x1 + x2 + x3)

termplot(fit, se = TRUE, terms = "x1")

enter image description here

termplot uses predict.lm(, type = "terms") for term-wise prediction. If a model has intercept (like above), predict.lm will centre each term (What does predict.glm(, type=“terms”) actually do?). In this way, each terms is predicted to be 0 at the mean of the covariate, and the standard error at the mean is 0 (hence the confidence interval intersects the line at the mean).

Community
  • 1
  • 1
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248