Marta Karas
Marta Karas

Reputation: 5165

Test if all elements of a list (lists themselves) are equal

I have a list of lists and want to check whether all elements of this list (which are of list type) are the same. How to make it in the fastest way?

Update: I put a reproducible example below. The point is to get a FALSE value of such a test, because two elements of the eventual.list are different: eventual.list[[1]][[1]] data.frame has other values than eventual.list[[2]][[1]] data.frame.

Code:

a <- 1:3
b <- 1:3
c <- 2:4

l1.el1 <- data.frame(a, b)
l1.el2 <- a
l1 <- list(l1.el1,
           l1.el2)

l2.el1 <- data.frame(a, c)
l2.el2 <- a
l2 <- list(l2.el1,
           l2.el2)

eventual.list <- list(l1,
                      l2)
eventual.list

Console output:

> eventual.list
[[1]]
[[1]][[1]]
  a b
1 1 1
2 2 2
3 3 3

[[1]][[2]]
[1] 1 2 3


[[2]]
[[2]][[1]]
  a c
1 1 2
2 2 3
3 3 4

[[2]][[2]]
[1] 1 2 3

Upvotes: 11

Views: 7413

Answers (1)

IRTFM
IRTFM

Reputation: 263421

This is the canonical method for determining whether all items in a list are the same:

length(unique(object))==1

In your case:

> length( unique( eventual.list ) )
[1] 2

> length( unique( eventual.list ) ) == 1
[1] FALSE

The help page for unique might have led one to think that lists would not be handled, until one reflects on this result that surprised me when I encountered it the first time:

 is.vector( eventual.list ) 
[1] TRUE

So lists are technically vectors in R parlance, they're just not 'atomic' vectors, they are "recursive".

>  is.atomic(eventual.list)
[1] FALSE
> is.recursive(eventual.list)
[1] TRUE

Upvotes: 30

Related Questions