测试列表的所有成员之间是否相等 [英] Test for equality between all members of list

查看:97
本文介绍了测试列表的所有成员之间是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查列表的所有成员之间是否相等的正确语法是什么?我发现

What is the right syntax to check equality between all members of a list? I found that

do.call(all.equal, list(1,2,3))

返回TRUE.

我的直觉是,它正在检查列表元素内的相等性,而不是两者之间.

My hunch is that it is checking equality within elements of a list, not between.

理想情况下,解决方案将忽略元素的名称,但不忽略元素组件的名称.例如,给定输入,它应该返回TRUE:

Ideally the solution would ignore the name of the element, but not those of the element components. For example, it should return TRUE given the input:

some_list <- list(foo = data.frame(a=1),
                  bar = data.frame(a=1))

但是FALSE给出了输入:

But FALSE given the input:

some_other_list <- list(foo = data.frame(a=1),
                        bar = data.frame(x=1))

但是我可以接受对元素名称敏感的解决方案.

But I could live with a solution that was sensitive to the name of the element.

编辑:显然,我需要复习?funprog.作为接受的答案的后续措施,值得注意以下行为:

Edit: Clearly I need to review ?funprog. As a follow-up to the accepted answer, it's worth noting the following behavior:

Reduce(all.equal, some_list)  # returns TRUE

Reduce(all.equal, some_other_list) #returns [1] "Names: 1 string mismatch"

对于:

yet_another_list <- list(foo = data.frame(a=1),
                        bar = data.frame(x=2))
Reduce(all.equal, yet_another_list)
# returns: [1] "Names: 1 string mismatch"     "Component 1: Mean relative difference: 1"


我的示例不足,并且在包含3个或更多元素的情况下Reduce不起作用:


Edit 2: My example was inadequate, and Reduce doesn't work in the case of 3 or more elements:

some_fourth_list <- list(foo = data.frame(a=1),
                  bar = data.frame(a=1),
                  baz = data.frame(a=1))
Reduce(all.equal, some_fourth_list) # doesn't return TRUE

推荐答案

1)如果该列表仅包含问题中的两个部分,请尝试以下操作:

1) IF the list has only two components as in the question then try this:

identical(some_list[[1]], some_list[[2]])
## [1] TRUE

2),或者对于具有任意数量组件的通用方法,请尝试以下操作:

2) or for a general approach with any number of components try this:

all(sapply(some_list, identical, some_list[[1]]))
## [1] TRUE

L <- list(1, 2, 3)
all(sapply(L, identical, L[[1]]))
## [1] FALSE

3)减少与以前的解决方案相比,这有点冗长,但是由于已经讨论了Reduce,因此可以采用以下方法:

3) Reduce This is a bit verbose compared to the prior solution but since there was a discussion of Reduce, this is how it could be jmplemented:

Reduce(function(x, y) x && identical(y, some_list[[1]]), init = TRUE, some_list)
## [1] TRUE

Reduce(function(x, y) x && identical(y, L[[1]]), init = TRUE, L)
## [1] FALSE

这篇关于测试列表的所有成员之间是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆