I am currently working with R and I'm trying to write a function that derives the partial residuals for a multiple linear model. I know that there are existing functions in R but I want to write a function myself.
However, my problem is that executing the function always returns numeric(0):
y <- c(2, 3, 6, 8, 12, 15)
x1 <- c(1, 1.5, 2.5, 4, 7, 9)
x2 <- c(10, 22, 30, 31, 38, 42)
fitlm <- lm(y ~ x1+x2)
PR <- function(fit, predictor)
{
PRes <- as.numeric(fit$residuals) + (fit$coefficients["predictor"]*fit$model$predictor)
return(PRes)
}
# with fit = name of linear model and predictor = name of predictor
PR_x1 <- PR(fitlm, x1)
PR_x2 <- PR(fitlm, x2)
but when I only execute the code outside the function everything works and I get the partial residuals:
as.numeric(fitlm$residuals)+fitlm$coefficients["x1"]*fitlm$model$x1
Does anybody know how to fix this? What am I doing wrong?
Thanks for your help!