R: How to include lm leftovers back in data.frame?

I am trying to return leftovers from lm ​​to the original data.frame file:

fit <- lm(y ~ x, data = mydata, weight = ind) mydata$resid <- fit$resid 

The second line usually works if the remainder is the same length as the number of lines mydata. However, in my case, some of the ind elements are NA . Therefore, the residual length is usually less than the number of lines. Also, fit$resid is a "numeric" vector, so for me there is no label to combine with mydata data.frame. Is there an elegant way to achieve this?

+4
source share
1 answer

I think this should be pretty easy if ind is just a vector.

 sel <- which(!is.na(ind)) mydata$resid <- NA mydata$resid[sel] <- fit$resid 
+7
source

Source: https://habr.com/ru/post/1485849/


All Articles