如何在R语言中对矩阵的每一行重复计算?

4

我非常非常新手编程和R语言。我试图寻找答案来解决我的问题,但问题的一部分是我不知道要搜索什么。

我试图将一个统计距离的计算重复应用到矩阵的每一行。以下是我目前的代码:

pollution1 <-as.matrix(pollution[,5:6])
ss <- var(pollution1)
ssinv <- solve(ss)
xbar <- colMeans(pollution1)
t(pollution1[1,]-xbar)%*%ssinv%*%(pollution1[1,]-xbar)

这只能获取第一个统计距离,但我不想重新输入此行以获得所有统计距离。

据我所知,我可能需要使用循环或apply(),但我自己没有成功。如有帮助,并且有关如何搜索帮助以便我不必发布的建议,将不胜感激。


欢迎来到 Stack Overflow!您能提供一个示例以帮助我们复现您的问题吗?https://dev59.com/eG025IYBdhLWcg3whGSx - agstudy
2个回答

3
你可能还需要考虑使用 mahalanobis 函数:来自 ?mahalanobis

Returns the squared Mahalanobis distance of all rows in ‘x’ and the vector mu = ‘center’ with respect to Sigma = ‘cov’. This is (for vector ‘x’) defined as

                  D^2 = (x - mu)' Sigma^-1 (x - mu)

当然,学习如何使用apply也是很好的...


2

只使用 apply 怎么样?

apply(pollution1, 1, function(i) t(i-xbar) %*% ssinv %*% (i-xbar))

此外,如果您能让您的示例可复制,将会很有帮助,例如:
pollution1 = matrix(rnorm(100), ncol=2)
ss = var(pollution1)
ssinv = solve(ss)
xbar = colMeans(pollution1)
t(pollution1[1,]-xbar) %*% ssinv %*% (pollution1[1,]-xbar)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接