Error when regressing on residuals of a previous regression. Why?

Viewed 29

I want to regress twice

dat <- read.csv("data/prices.csv")
reg1a <- lm(dat$size~dat$rooms)
reg1b <- lm(dat$rent,reg1a$residuals)

Running reg1a is not a problem. Then I want to regress variable rent from dat on the residuals from the first regression reg1a. However I get this error message. What am I doing wrong?

Error in formula.default(object, env = baseenv()) : invalid formula

1 Answers

You are missing the ~ in reg1b, so lm() thinks your formula is just dat$rent, which is not a valid formula. Changing it to

reg1b <- lm(dat$rent~reg1a$residuals)

should remove the error.

Related