5

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!

Seb
  • 5,265
  • 7
  • 29
  • 49

2 Answers2

9

After some search I think I found an alternative

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

should do the trick. right?

Seb
  • 5,265
  • 7
  • 29
  • 49
4
dataf$fit2 <- NA
dataf$fit2[!is.na(dataf$wt)] <- fitted(fit2)
Roland
  • 122,144
  • 10
  • 182
  • 276