Mr.*_*Zen 1 r max matrix vectorization
假设您要从相应的行中减去矩阵的每一行的最大值.你可以使用这样的循环来做到这一点:
# create matrix
mat <- matrix(rnorm(100),ncol=5,nrow=20)
for(i in 1:nrow(mat)){ #for each row
row.max <- max( mat[i,] ) #take the maximum of the row
mat[i,] <- mat[i,] - row.max #subtract it from the row
}
Run Code Online (Sandbox Code Playgroud)
我想到的方式在量化的方式来做到这一点,也许使用max.col(),但是,我不能来的东西为止.有任何想法吗?
谢谢!
编辑:
谢谢你的回答,我接受了(迄今为止)最快的解决方案.
Unit: microseconds
expr min lq mean median uq max neval
loop 4671.687 4906.6820 5124.78995 5019.7965 5214.5935 12318.986 100
apply 41.055 47.0430 60.58208 57.0925 71.6320 158.661 100
rowMaxs 2.139 2.9945 6.21019 5.3465 8.9810 12.402 100
do.call 111.618 125.0890 154.46904 142.4095 170.2065 422.522 100
Run Code Online (Sandbox Code Playgroud)
你可以使用library(matrixStats),只需使用,
mat - rowMaxs(mat)
Run Code Online (Sandbox Code Playgroud)
如行中所示matrixStats,此解决方案非常闪电.(@hrbrmstr提供的基准测试)
## Unit: microseconds
## expr min lq mean median uq max neval
## base_mat 33.084 39.3215 46.93637 46.3575 49.6435 116.293 100
## base_df 80.769 98.9870 116.05771 112.8985 127.6595 201.791 100
## matrixStats 2.111 3.0170 4.99795 4.9655 5.8415 27.240 100
## qlcMatrix 716.229 742.2140 834.73351 782.1605 888.4960 1491.734 100
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |