检查列表的所有元素是否在R中相等 [英] check whether all elements of a list are in equal in R
问题描述
我有一个列表的几个向量。我想检查列表中的所有向量是否相等。有相同
,只适用于成对比较。所以我写了下面的功能,看起来丑陋我。仍然我没有找到一个更好的解决方案。这是我的RE:
test_true< - list(a = c(1,2,3),b = c ,2,3),d = c(1,2,3))
test_false < - list(a = c(1,2,3),b = c = c(1,32,13))
compareList < - function(li){
stopifnot(length(li)> 1)
l < li)
res< - lapply(li [-1],function(X,x)identical(X,x),x = li [[1]])
res& unlist(res))
res
}
compareList(test_true)
compareList(test_false)
有任何建议吗?
allSame < - function(x)length(unique(x))== 1
allSame(test_true)
# [1] TRUE
allSame(test_false)
#[1] FALSE
正如@JoshuaUlrich在下面指出的, unique
在列表上可能很慢。此外,相同
和 unique
可以使用不同的标准。 减少
是我最近学到的扩展成对操作的函数:
sameValue < - function(x,y)if(identical(x,y))x else FALSE
减少(identicalValue,test_true)
#[1] ,test_false)
#[1] FALSE
这样无效地继续进行比较, -匹配。我的原始解决方案是写 else break
而不是 else FALSE
,抛出一个错误。
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?
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.
这篇关于检查列表的所有元素是否在R中相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!