有几种计算数据样本x方差的数值稳健和精确的算法。例如,有一个精度很高的公式(参见下面的参考文献),大致相当于
( sum((x - mean(x))^2) - (sum(x - mean(x))^2)/length(x) )/length(x)这有点低效,因为它会进行两次数据传递。另一方面,数学上等价的公式mean(x^2)-mean(x)^2更容易被灾难性地取消。还有许多其他算法,其中一些算法只对数据进行一次遍历;例如,请参阅Chan,Golub,LeVeque或铃儿中的评论。
R在遮罩下使用哪种算法计算与函数var()的方差?我阅读了该函数的手册页,但它们没有提到所使用的具体算法。我不是程序员,很难理解底层C代码中发生了什么。
发布于 2021-12-21 06:24:40
如果您正在寻找stats::var,只需键入它。
stats::var
function (x, y = NULL, na.rm = FALSE, use)
{
if (missing(use))
use <- if (na.rm)
"na.or.complete"
else "everything"
na.method <- pmatch(use, c("all.obs", "complete.obs",
"pairwise.complete.obs", "everything", "na.or.complete"))
if (is.na(na.method))
stop("invalid 'use' argument")
if (is.data.frame(x))
x <- as.matrix(x)
else stopifnot(is.atomic(x))
if (is.data.frame(y))
y <- as.matrix(y)
else stopifnot(is.atomic(y))
.Call(C_cov, x, y, na.method, FALSE)
}
<bytecode: 0x000001f7636f08f8>
<environment: namespace:stats>在.Call(C_cov,...)中,它调用C对象cov.c。您可以在该链接中找到var的算法。
https://stackoverflow.com/questions/70431321
复制相似问题