本文介绍了用NA替换矩阵中的0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用NA替换矩阵中所有零的最有效方法是什么?

What is most efficient way to replace all zeros in matrix with NAs?

我做什么:

my_matrix[my_matrix==0] <- NA

我在推荐系统中需要它( recommenderlab ).填写NA与建立推荐系统的时间相同.

I need it for recommender system (recommenderlab). Filling NAs take same time as building recommender system.

dim(my_matrix)〜500000x500

dim(my_matrix) ~ 500000x500

零为90%.

推荐答案

答案和基准

my_matrix <- matrix(1:5e5, ncol=50)
my_matrix[4000:5000, 3:10] <- 0

library(microbenchmark)
microbenchmark(
  insubset     = my_matrix[my_matrix %in% 0],
  replace1     = replace(my_matrix, my_matrix %in% 0, NA),
  replace2     = replace(my_matrix, which( my_matrix==0), NA),
  Aleksandro   = my_matrix[my_matrix==0] <- NA,
  excloperator = my_matrix[!my_matrix] <- NA,
  is.na        = is.na(my_matrix) <- which(my_matrix == 0)
)

Unit: milliseconds
         expr       min        lq      mean    median        uq        max neval
     insubset 22.579762 22.890431 26.197510 23.453346 25.210976 151.957848   100
     replace1 21.630386 23.621707 27.573375 25.643425 26.225683 104.389554   100
     replace2  3.979487  4.069095  4.872796  4.159493  6.449839   8.887427   100
   Aleksandro 12.787962 13.100210 14.837055 13.689376 14.098338  96.258866   100
 excloperator 11.894246 12.275969 13.541593 13.011391 15.144429  17.307862   100
        is.na  7.642823  8.901978   15.7352  9.342954  10.13166   68.31235   100

这篇关于用NA替换矩阵中的0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 10:30