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

前端 未结 5 589
挽巷
挽巷 2021-01-02 09:34

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.

5条回答
  •  礼貌的吻别
    2021-01-02 10:27

    How about

    allSame <- function(x) length(unique(x)) == 1
    
    allSame(test_true)
    # [1] TRUE
    allSame(test_false)
    # [1] FALSE
    

    As @JoshuaUlrich pointed out below, unique may be slow on lists. Also, identical and unique may use different criteria. Reduce is a function I recently learned about for extending pairwise operations:

    identicalValue <- function(x,y) if (identical(x,y)) x else FALSE
    Reduce(identicalValue,test_true)
    # [1] 1 2 3
    Reduce(identicalValue,test_false)
    # [1] FALSE
    

    This inefficiently continues making comparisons after finding one non-match. My crude solution to that would be to write else break instead of else FALSE, throwing an error.

提交回复
热议问题