Kush Patel
Kush Patel

Reputation: 3865

Check List to find out all values are same in R

I have list as follows

l = list(c("a", "b", "c"), c("a", "b", "c"), c("a", "b", "c"))

I want to check that each of them contain same values using apply family functions.

I want following answer

TRUE, TRUE, TRUE

Upvotes: 1

Views: 348

Answers (2)

C8H10N4O2
C8H10N4O2

Reputation: 19005

If you really want to use the apply family, you could do something like:

l = list(c("a", "b", "c"), c("a", "b", "c"), c("a", "b", "c"))
sapply(l, function(x) all.equal(x, l[[1]]))
# returns [1] TRUE TRUE TRUE
l = list(c("a", "b", "c"), c("a", "b", "c"), c("a", "b", "x"))
sapply(l, function(x) all.equal(x, l[[1]]))
# returns [1] "TRUE" "TRUE" "1 string mismatch"

Upvotes: 2

akrun
akrun

Reputation: 887531

We can use duplicated

duplicated(l)|duplicated(l, fromLast=TRUE)
#[1] TRUE TRUE TRUE

If we need to compare all the combinations of list elements, combn is another way

combn(seq_along(l), 2, FUN= function(x) all(l[[x[1]]] == l[[x[2]]]))
#[1] TRUE TRUE TRUE

Upvotes: 3

Related Questions