Are residuals in linear regression following same order of original data frame row?

StackOverflow https://stackoverflow.com/questions/20506984

  •  31-08-2022
  •  | 
  •  

Pregunta

After I fit a multiple linear regression model, I want to merge the residuals with original data frame. But I found that the residuals is a vector that does not have the original row names attached to each residual.

Are the residuals following the same order of the row names for original data frame? Is there a way to check this correspondence?

dat <- read.table("myData.txt", header = T)
dat.str <- data.frame(dat$response, dat$v1, dat$v2)
dat.lm <- lm(dat.str$response ~ dat$v1 + dat$v2)
dat.residual <- residuals(dat.lm)

Now I want to merge dat.residual back to "dat". How can I make sure that the merging happens to rows with same rownames?

¿Fue útil?

Solución

To reassure yourself that they are in the right order, you could run a quick graphical check like this:

m <- lm(mpg~hp, data=mtcars)
plot(predict(m) + residuals(m) ~ dat$mpg, data=mtcars) 

enter image description here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top