ifelse() must be used with caution

The if else statement is very useful when you work with a vector, but take care, it must be used with caution because it can be very slow :

Aini =  runif(1000000, min=-1,max=1)
library(microbenchmark)
A <- Aini
microbenchmark({B1 <- ifelse( A < 0, sqrt(-A), A )})
# mean = 77.55551
A <- Aini
microbenchmark({B2 <- ifelse( A < 0, suppressWarnings(sqrt(-A)), A )})
# mean = 76.53762
A <- Aini
microbenchmark({B3 <- ifelse( A < 0, sqrt(abs(A)), A )})
# mean = 75.26712
A <- Aini
microbenchmark({A[A < 0] <- sqrt(-A[A < 0]);B4 <- A})
# mean = 17.71883

Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

stepAIC from package MASS with AICc

Install treemix in ubuntu 20.04