我想在 mahanalobis 函数中用 ginv()
替换solve()
。
有没有办法强制R中的任何函数使用ginv()
而不是solve()
?
mahalanobis
函数非常简单。 为什么不用适当的替换来定义你自己的,即
mahalanobis_ginv <- function (x, center, cov,
inverted = FALSE, ...) {
x <- if (is.vector(x))
matrix(x, ncol = length(x))
else as.matrix(x)
if (!identical(center, FALSE))
x <- sweep(x, 2L, center)
if (!inverted)
cov <- MASS::ginv(cov, ...)
setNames(rowSums(x %*% cov * x), rownames(x))
}
从?mahalanobis
:
ma <- cbind(1:6, 1:3)
(S <- var(ma))
mahalanobis(c(0, 0), 1:2, S) ## 5.37037
mahalanobis_ginv(c(0, 0), 1:2, S) ## 5.37037
您可以键入 trace(mahalanobis, edit = T) 并进行必要的替换。点击保存时,对函数所做的更改将仅存储为当前 R 会话。
为什么不试试
cov <- solve(ginv(sigma))