本文介绍了检查列表的所有元素是否在R中相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个列表的几个向量。我想检查列表中的所有向量是否相等。有相同,只适用于成对比较。所以我写了下面的功能,看起来丑陋我。仍然我没有找到一个更好的解决方案。这是我的RE: test_true< - list(a = c(1,2,3),b = c ,2,3),d = c(1,2,3)) test_false compareList stopifnot(length(li)> 1)l res< - lapply(li [-1],function(X,x)identical(X,x),x = li [[1]]) res& unlist(res)) res } compareList(test_true) compareList(test_false) 有任何建议吗? 解决方案 allSame allSame(test_true)# [1] TRUE allSame(test_false)#[1] FALSE 正如@JoshuaUlrich在下面指出的, unique 在列表上可能很慢。此外,相同和 unique 可以使用不同的标准。 减少是我最近学到的扩展成对操作的函数: sameValue 减少(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 aboutallSame <- function(x) length(unique(x)) == 1allSame(test_true)# [1] TRUEallSame(test_false)# [1] FALSEAs @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 FALSEReduce(identicalValue,test_true)# [1] 1 2 3Reduce(identicalValue,test_false)# [1] FALSEThis 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中相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-15 16:56