Check equality between all members of the list

What is the correct syntax for checking equality between all members of a list? I found that

do.call(all.equal, list(1,2,3))

returns TRUE.

My hunch is that it checks for equality within list items, not between them.

Ideally, the solution ignores the name of the element, but the wrong components of the element. For example, it should return TRUE given input:

some_list <- list(foo = data.frame(a=1),
                  bar = data.frame(a=1))

But FALSE given input:

some_other_list <- list(foo = data.frame(a=1),
                        bar = data.frame(x=1))

But I could live with a solution that is sensitive to the name of the element.


Edit : I have to consider ?funprog. In response to the accepted answer, the following should be noted:

Reduce(all.equal, some_list)  # returns TRUE

Reduce(all.equal, some_other_list) #returns [1] "Names: 1 string mismatch"

And for:

yet_another_list <- list(foo = data.frame(a=1),
                        bar = data.frame(x=2))
Reduce(all.equal, yet_another_list)
# returns: [1] "Names: 1 string mismatch"     "Component 1: Mean relative difference: 1"

Edit 2: My example is inadequate, and Reducedoes not work in case of 3 or more elements:

some_fourth_list <- list(foo = data.frame(a=1),
                  bar = data.frame(a=1),
                  baz = data.frame(a=1))
Reduce(all.equal, some_fourth_list) # doesn't return TRUE
+4
2

1) , , :

identical(some_list[[1]], some_list[[2]])
## [1] TRUE

2) :

all(sapply(some_list, identical, some_list[[1]]))
## [1] TRUE

L <- list(1, 2, 3)
all(sapply(L, identical, L[[1]]))
## [1] FALSE

3) . , , Reduce, :

Reduce(function(x, y) x && identical(y, some_list[[1]]), init = TRUE, some_list)
## [1] TRUE

Reduce(function(x, y) x && identical(y, L[[1]]), init = TRUE, L)
## [1] FALSE
+3

:

identical(unlist(some_list), unlist(some_other_list))
0

Source: https://habr.com/ru/post/1620352/


All Articles