休息一下实施弗兰克的解决方案:
all.identical <- function(l) class(try(Reduce(function(x, y) if(identical(x, y)) x else break, l), silent = TRUE)) != "try-error"
继续 Artem 的基准测试并添加 Jake 评论中的解决方案,速度很大程度上取决于被比较的对象:
library(microbenchmark)
all.identical <- function(l) !is.null(Reduce(function(x, y) if(identical(x, y)) x else NULL, l))
all.identical.beak <- function(l) class(try(Reduce(function(x, y) if(identical(x, y)) x else break, l), silent = TRUE)) != "try-error"
comp_list4 <- function(l) sum(duplicated.default(l)) == length(l) - 1L
comp_list5 <- function(l) all(duplicated.default(l)[-1])
x1 <- as.list(as.data.frame(replicate(1000, 1:100)))
x2 <- as.list(as.data.frame(replicate(1000, sample(100))))
microbenchmark(all.identical(x1), all.identical.beak(x1), comp_list4(x1), comp_list5(x1))
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> all.identical(x1) 1060.2 1145.30 1396.207 1208.40 1433.25 4628.9 100
#> all.identical.beak(x1) 1081.1 1150.55 1345.244 1202.90 1334.50 5051.9 100
#> comp_list4(x1) 190.4 201.05 269.145 205.65 228.65 4225.8 100
#> comp_list5(x1) 195.8 207.60 267.277 218.35 250.30 3214.7 100
microbenchmark(all.identical(x2), all.identical.beak(x2), comp_list4(x2), comp_list5(x2))
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> all.identical(x2) 997.2 1058.30 1199.814 1113.50 1195.75 3309.2 100
#> all.identical.beak(x2) 101.6 110.60 136.213 118.10 136.00 361.9 100
#> comp_list4(x2) 152.5 161.05 188.098 168.95 196.15 418.4 100
#> comp_list5(x2) 156.0 165.30 191.243 172.85 194.65 638.2 100
x1 <- as.list(as.data.frame(replicate(10, 1:1e5)))
x2 <- as.list(as.data.frame(replicate(10, sample(1e5))))
microbenchmark(all.identical(x1), all.identical.beak(x1), comp_list4(x1), comp_list5(x1))
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> all.identical(x1) 391.1 435.75 491.762 459.95 500.80 1038.0 100
#> all.identical.beak(x1) 420.5 444.60 525.837 470.60 541.40 1542.8 100
#> comp_list4(x1) 1506.8 1596.65 1707.656 1645.80 1784.00 2241.0 100
#> comp_list5(x1) 1502.2 1583.55 1696.311 1647.65 1759.25 2275.6 100
microbenchmark(all.identical(x2), all.identical.beak(x2), comp_list4(x2), comp_list5(x2))
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> all.identical(x2) 11.0 13.35 16.623 14.60 16.40 81.9 100
#> all.identical.beak(x2) 87.1 99.00 132.218 114.40 144.95 472.5 100
#> comp_list4(x2) 1127.6 1184.90 1286.094 1219.80 1298.90 2463.2 100
#> comp_list5(x2) 1124.9 1189.85 1291.297 1221.65 1301.60 2569.1 100
Created on 2021-12-02 by the reprex package (v2.0.1)