'replace default solve() by ginv
I want to replace solve()
by ginv()
in the mahanalobis function.
Is there any way to force any functions in R to use ginv()
instead of solve()
?
Solution 1:[1]
The mahalanobis
function is pretty simple. Why not just define your own with the appropriate substitution, i.e.
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))
}
From ?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
Solution 2:[2]
You could type trace(mahalanobis, edit = T) and make the necessary replacements. When hitting save changes made to the function will only be stored for the current R session.
Solution 3:[3]
why not try
cov <- solve(ginv(sigma))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ben Bolker |
Solution 2 | SlevinKelevra |
Solution 3 | m872384296 |