Check if all list items (lists) are equal

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

Update: I will give an example of reproducibility below. The point is to get the FALSE value of such a test, since the two eventual.list elements eventual.list different: eventual.list[[1]][[1]] data.frame has different 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]] ab 1 1 1 2 2 2 3 3 3 [[1]][[2]] [1] 1 2 3 [[2]] [[2]][[1]] ac 1 1 2 2 2 3 3 3 4 [[2]][[2]] [1] 1 2 3 
+6
source share
1 answer

This is a 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 could make you think that the lists will not be processed until it reflects on this result, which surprised me when I came across it for the first time:

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

Thus, lists are technically vectors in R parlance, they simply are not “atomic” vectors, they are “recursive”.

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

All Articles