在r中执行函数内部函数的调用

时间:2014-07-11 11:54:13

标签: r function call match lm

我想通过自己创建函数lm()来重现它。我已经编写了代码来查找系数,vcov,sigma和df,但是我无法理解如何在函数本身内调用我创建的函数(即“linMod”)。我知道我应该使用“match.call”,但我从来没有使用它,我对它的工作方式有点困惑。

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))


}

所以,为了使它更清楚..例如,我使用带有参数
的函数      r包“MASS”的linMod(Hwt~Bwt + Sex,data = cats),调用应该如下:

$call
linMod(formula = Hwt ~ Bwt + Sex, data = cats)

与lm()函数一样。

1 个答案:

答案 0 :(得分:2)

尝试以下方法:

call = match.call()
相关问题