I have a list of several vectors. I would like to check whether all vectors in the list are equal. There\'s identical
which only works for pairwise comparison.
How about
allSame <- function(x) length(unique(x)) == 1
allSame(test_true)
# [1] TRUE
allSame(test_false)
# [1] FALSE
As @JoshuaUlrich pointed out below, unique
may be slow on lists. Also, identical
and unique
may use different criteria. Reduce
is a function I recently learned about for extending pairwise operations:
identicalValue <- function(x,y) if (identical(x,y)) x else FALSE
Reduce(identicalValue,test_true)
# [1] 1 2 3
Reduce(identicalValue,test_false)
# [1] FALSE
This inefficiently continues making comparisons after finding one non-match. My crude solution to that would be to write else break
instead of else FALSE
, throwing an error.