Reputation: 325
I want to reproduce the function lm() by making it on my own. I've already wrote the code to find coefficients, vcov, sigma and df, but I can't understand how to make the call of the function I created (namely "linMod") inside the function itself. I know that I should use "match.call", but I've never used it and I'm a little bit confused about how it works.
linMod <- function(formula,data){
mf <- model.frame(formula=formula, data=data)
x <- model.matrix(attr(mf, "terms"), data=mf)
y <- model.response(mf)
## compute (x'x)^(-1)
x_1 <- solve(crossprod(x,x))
## compute beta
beta <- tcrossprod(x_1,x)%*%y
## calculate degrees of freedom
df <- nrow(x)-ncol(x)
## calculate sigma^2
sig <- y-(x%*%beta)
sigma2 <- crossprod(sig,sig)/df
sigma <- sqrt(sigma2)
##compute vcov
vcov <- as.vector(sigma2)*x_1
# I create a call here -> match.call(), right?
return(list("coefficients" = beta,
"vcov" = vcov,
"df" = df,
"sigma" = sigma,
"call" = #call of the linMod function itself))
}
So, to make it more clear.. If for example I use the function with the arguments
linMod(Hwt ~ Bwt + Sex, data = cats) of the r package "MASS", the call should look like:
$call
linMod(formula = Hwt ~ Bwt + Sex, data = cats)
as in the lm() function.
Upvotes: 0
Views: 922