Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace 0 in matrix with NA

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

What I do:

my_matrix[my_matrix==0] <- NA

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

EDIT 1:

dim(my_matrix) ~ 500000x500

Where zeros are ~90%.

like image 453
Aleksandro M Granda Avatar asked May 19 '15 15:05

Aleksandro M Granda


1 Answers

Answers and a benchmark

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
like image 135
Pierre L Avatar answered Oct 12 '22 23:10

Pierre L