我试图测试一个向量的所有元素是否相等。我提出的解决方案似乎有些迂回,都涉及检查 length()
。
x <- c(1, 2, 3, 4, 5, 6, 1) # FALSE
y <- rep(2, times = 7) # TRUE
unique()
:
length(unique(x)) == 1
length(unique(y)) == 1
rle()
:
length(rle(x)$values) == 1
length(rle(y)$values) == 1
一个解决方案,将让我包括一个容忍值的评估’平等’之间的元素将是理想的,以避免 FAQ 7.31问题。
Is there a built-in function for type of test that I have completely overlooked? identical()
and all.equal()
compare two R objects, so they won't work here.
编辑1
下面是一些基准测试结果:
library(rbenchmark)
John <- function() all( abs(x - mean(x)) < .Machine$double.eps ^ 0.5 )
DWin <- function() {diff(range(x)) < .Machine$double.eps ^ 0.5}
zero_range <- function() {
if (length(x) == 1) return(TRUE)
x <- range(x) / mean(x)
isTRUE(all.equal(x[1], x[2], tolerance = .Machine$double.eps ^ 0.5))
}
x <- runif(500000);
benchmark(John(), DWin(), zero_range(),
columns=c("test", "replications", "elapsed", "relative"),
order="relative", replications = 10000)
结果是:
test replications elapsed relative
2 DWin() 10000 109.415 1.000000
3 zero_range() 10000 126.912 1.159914
1 John() 10000 208.463 1.905251
看起来 diff(range(x)) < .Machine$double.eps ^ 0.5
是最快的。