Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

merge

r

lm

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!

like image 965
Seb Avatar asked Aug 16 '12 15:08

Seb


2 Answers

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?

like image 106
Seb Avatar answered Nov 08 '22 03:11

Seb


dataf$fit2 <- NA
dataf$fit2[!is.na(dataf$wt)] <- fitted(fit2)
like image 37
Roland Avatar answered Nov 08 '22 03:11

Roland