Match the setpoints from `lm ()` with the data frame for `NA`

This should be a really trivial question, but I'm struggling to find a solution. Here is my problem:

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 get the second example to work? I tried the solution using row.names in model.matrix() , but this does not work when I include certain factors in my regression (this was reported as a bug if I understand it correctly). Thanks for your kind help!

+4
source share
2 answers

After some searching, I think I found an alternative

 dataf[2,]<-NA summary(fit2 <- lm(mpg ~ wt, data=dataf, na.action="na.exclude")) dataf$fit2 <- fitted(fit2) 

gotta do the trick. is not it?

+6
source
 dataf$fit2 <- NA dataf$fit2[!is.na(dataf$wt)] <- fitted(fit2) 
+4
source

All Articles