I am trying to compare vector a of objects using Reduce
- all.equal does not work
- == works for numericals but will not be sufficient for objects.
I would prefer a solution that does not use existing packages but R core functions only
Example (Simplified to use numeric vectors instead of objects):
test <- c(1,1,1,1,1)
Reduce("==",test)
[1] TRUE
I do not understand why == works while all.equal does not
Reduce(all.equal,test)
[1] "Modes: character, numeric"
[2] "Lengths: 3, 1"
[3] "target is character, current is numeric"
Final remark:
This is not a duplicate. I am interested in a solution that compares objects not numeric values
Comparison of the elements of a vector of numeric values: See existing solution on stackoverflow Test for equality among all elements of a single numeric vector
CodePudding user response:
You can try identical
in sapply
and compare each with the first element.
x <- list(list(1), list(1))
all(sapply(x[-1], identical, x[[1]]))
#[1] TRUE
x <- list(list(1), list(2))
all(sapply(x[-1], identical, x[[1]]))
#[1] FALSE
CodePudding user response:
Here is a function returning TRUE if all pairwise comparisons of the elements inside a list were identical:
all_pairs_equal <- function(elements) {
all(mapply(function(x, y) identical(elements[x], elements[y]), 1, seq(1, length(elements))))
}
all_pairs_equal(list(iris, iris, iris))
#> [1] TRUE
all_pairs_equal(list(1, 1, 1))
#> [1] TRUE
all_pairs_equal(list(iris, iris, 2))
#> [1] FALSE
Created on 2021-10-05 by the reprex package (v2.0.1)