【问题标题】:Do a call of a function inside the function itself in r在 r 中调用函数本身内部的函数
【发布时间】:2014-07-11 11:54:12
【问题描述】:

我想通过自己制作来重现函数 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() 函数中一样。

【问题讨论】:

  • 你总是可以通过不带括号的写出函数名来查看函数的代码,例如lm。然后你可以看到事情是如何实现的。 lm 的第三行是 cl &lt;- match.call(),它被添加到返回列表末尾前几行 z$call &lt;- cl
  • 谢谢!没想到..

标签: r function call match lm


【解决方案1】:

尝试以下方法:

call = match.call()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 2012-10-17
    • 1970-01-01
    • 2012-01-12
    • 2010-12-09
    • 2021-10-24
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多