Test for equality of all vector elements
Lets try 4 methods:
Using https://www.geeksforgeeks.org/r-language/test-for-equality-of-all-vector-elements-in-r/ as reference
Clearly the best solution is all(x[1] == x) or any(x[1] != x)
> library(microbenchmark)
> x <- runif(10000000)
> microbenchmark({all(x[1] == x)}, {any(x[1] != x)},
+ {length(unique(x)) != 1}, {var(x) != 0})
Unit: milliseconds
expr min lq mean median uq max neval
{ all(x[1] == x) } 9.196095 9.388385 11.34733 9.563066 10.537984 119.53070 100
{ any(x[1] != x) } 9.108806 9.328279 10.06885 9.489880 9.731493 13.43574 100
{ length(unique(x)) != 1 } 296.034719 301.525357 307.24105 304.064159 306.682849 414.65723 100
{ var(x) != 0 } 28.685855 29.400464 29.79199 29.736398 29.981127 35.97016 100
>
> x <- rep(1298, 10000000)
> microbenchmark({all(x[1] == x)}, {any(x[1] != x)},
+ {length(unique(x)) != 1}, {var(x) != 0})
Unit: milliseconds
expr min lq mean median uq max neval
{ all(x[1] == x) } 17.98383 18.19519 19.74683 18.31884 18.58518 128.02414 100
{ any(x[1] != x) } 18.01167 18.25332 19.04143 18.47964 18.88122 23.25672 100
{ length(unique(x)) != 1 } 62.05457 65.59533 68.04618 66.06650 66.75036 172.14531 100
{ var(x) != 0 } 29.30688 29.63464 30.10617 29.76778 30.00218 52.30924 100
Commentaires
Enregistrer un commentaire