Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check whether all elements of a list are in equal in R

Tags:

comparison

r

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. So I wrote the following function which looks ugly to me. Still I did not find a better solution. Here's my RE:

test_true <- list(a=c(1,2,3),b=c(1,2,3),d=c(1,2,3))
test_false <- list(a=c(1,2,3),b=c(1,2,3),d=c(1,32,13))

compareList <- function(li){
  stopifnot(length(li) > 1)
  l <- length(li)
  res <- lapply(li[-1],function(X,x) identical(X,x),x=li[[1]])
  res <- all(unlist(res))
  res
}

compareList(test_true)
compareList(test_false)

Any suggestions? Are there any native checks for identical for more than just pairwise comparison?

like image 620
Matt Bannert Avatar asked Sep 15 '13 14:09

Matt Bannert


People also ask

How do you check if all elements in list are the same?

Check if all elements in a list are identical or not using count() By counting the number of times the first element occurs in the list, we can check if the count is equal to the size of the list or not.

How do I compare elements in a list in R?

Compare equal elements in two R lists Third, you can also compare the equal items of two lists with %in% operator or with the compare. list function of the useful library. The result will be a logical vector.

How do I check if values are equal in R?

The Equality Operator == For example, you can check whether two objects are equal (equality) by using a double equals sign == . We can see if the logical value of TRUE equals the logical value of TRUE by using this query TRUE == TRUE .

How do you check if all elements in a vector are equal in R?

Method 2: Using length() and unique() function By using unique function if all the elements are the same then the length is 1 so by this way if the length is 1, we can say all elements in a vector are equal.


1 Answers

I woud do:

all.identical <- function(l) all(mapply(identical, head(l, 1), tail(l, -1)))

all.identical(test_true)
# [1] TRUE
all.identical(test_false)
# [1] FALSE
like image 65
flodel Avatar answered Oct 28 '22 19:10

flodel