Match fitted values from `lm()` with a data frame in case of `NA` values

Viewed 3450

This must be a really trivial question but I'm struggeling to get a solution. Here is my problem:

this works

#I run a simple regression
 data(mtcars)
 dataf <- mtcars
 summary(fit1 <- lm(mpg ~ wt,  data=dataf))

#Then I merge the fitted values with the data frame
 dataf$fit <- fitted(fit1)

This (of course) doesn't work

 dataf[2,]<-NA
 summary(fit2 <- lm(mpg ~ wt,  data=dataf))
#of course the NA value reduces my lm output
 dataf$fit2 <- fitted(fit2)

Error in `$<-.data.frame`(`*tmp*`, "fit2", value = c(23.3189679389035,  : 
replacement has 31 rows, data has 32

but how do I geht the second example to work? I tried a solution via the row.names in model.matrix() but this does not work when I include certain factors in my regression (this has been reported as a bug if I understand this correctly). Thank you for your kind help!

2 Answers
Related