在列表的两个元素中捕获值的不相等 [英] Capture non-equality of values in two elements of a list
本文介绍了在列表的两个元素中捕获值的不相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建 if()
条件以捕获 list()
的 x
元素中的值不完全相同的情况 list()
的 y
元素中的 OR 值在两种情况下都不都是相同的 OR .
I want to create if()
conditions to capture when values in the x
element of a list()
are not all the same OR values in the y
element of a list()
are not all the same OR both situations together.
为具体起见,我在下面提供了4个带有预期警告的列表.
For concreteness, I have provided 4 lists with the expected warnings below.
在R中有可能吗?
A = list(x = c(1,1,1,1), y = c(2,4,3,3)) # Expect warning that says `y` is bad!
B = list(x = c(1,2,1,1), y = c(3,3,3,3)) # Expect warning that says `x` is bad!
C = list(x = c(1,2,1,1), y = c(3,2,3,3)) # Expect warning that says `x` and `y` are bad!
D = list(x = c(1,1,1,1), y = c(3,3,3,3)) # Expect no warning !
推荐答案
我们可以创建一个条件来检查元素中每个元素中 unique
元素的 length
列表
We could create a condition to check the length
of unique
elements in each of the elements in the list
f1 <- function(lst_obj) {
v1 <- sapply(lst_obj, function(x) length(unique(x)))
i1 <- names(which(v1 != 1))
if(length(i1) == 1) {
warning(paste(i1, " is bad!"))
} else if(length(i1) > 1) {
warning(paste(i1, collapse = ' and '), " are bad!")
}
}
f1(A)
#Warning message:
#In f1(A) : y is bad!
f1(B)
#Warning message:
#In f1(B) : x is bad!
f1(C)
#Warning message:
#In f1(C) : x and y are bad!
f1(D)
这篇关于在列表的两个元素中捕获值的不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文