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
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
Enregistrer un commentaire