2

如何通过将每个原始值除以原始矩阵中该列的原始值平方和的平方根来获得。

data(longley)
X <- as.matrix(longley[,-7])

X/sqrt(colSums(X^2))

得到错误的结果。

4

2 回答 2

5

试试这个:

t(t(X)/sqrt(colSums(X^2)))

基准:

library(microbenchmark)
microbenchmark(t(t(X)/sqrt(colSums(X^2))),
               apply(X, 2 , function(x) x/sqrt(sum(x^2))))
# Unit: microseconds
#                                      expr     min       lq   median       uq     max neval
# t(t(X)/sqrt(colSums(X^2)))                 28.783  33.1305  34.9455  40.5640  68.147   100
# apply(X, 2, function(x) x/sqrt(sum(x^2))) 100.307 105.1940 106.9975 108.1075 193.015   100
于 2013-06-15T09:26:13.583 回答
4

这行得通吗?

data(longley)
X <- as.matrix(longley[,-7])

X <- apply(X, 2 , function(x) x/sqrt(sum(x^2)))
于 2013-06-15T09:10:14.893 回答