从同一列表的元素中查找零位置的不匹配 [英] Finding mismatches in zero positions from elements of the same list
问题描述
我想知道如何创建 if()
条件以捕获 list()
的一个元素中的 0
值不是<相同的 list()
的第二个元素中对应位置的code> 0 ?
I wonder how to create a if()
condition to capture when 0
values in one element of a list()
are not 0
for the corresponding positions in the second element of the same list()
?
例如,在 A
列表中, x
的前两个值是 0
,而 y的前两个值
不是 0
.因此,我想将其捕获为 error
( stop
).
For example, in A
list, the first two values of x
are 0
, but the first two values of y
are NOT 0
. So, I want to catch this as an error
(stop
).
但是,在 B
列表中, x
的前三个值是 0
,而 y
也是 0
.所以,我想将此作为( warning
).
However, in B
list, the first three values of x
are 0
, and the first three values of y
are 0
as well. So, I want to catch this as a (warning
).
在所有其他类型的 list
(例如下面的列表 C
)中,我不希望 warning
或 stop
.
In ALL other types of list
(e.g., list C
below), I want no warning
or stop
.
( A = list(x = c(0,0,2,2), y = c(3,3,1,1)) ) # `stop()`
( B = list(x = c(0,0,0,1,1,1), y = c(0,0,0,1,1,1)) ) # `warning()`
( C = list(x = c(5,5,5), y=c(1,1,1)) ) # no `stop` or `warning`.
推荐答案
这是尝试解决您的问题的方法.
here is a try to resolve your issue.
这取决于介于0和Inf之间的值,以及矢量具有相同的长度.我认为,如果您愿意,它可以在2种以上的向量上工作.
It depend on the values being between 0 and Inf, and the vector having the same length. I think it works on more than 2 vector if you want.
( A = list(x = c(0,0,2,2), y = c(3,3,1,1)) ) # Expect error
( B = list(x = c(0,0,0,1,1,1), y = c(0,0,0,1,1,1)) ) # Expect warning
( C = list(x = c(5,5,5), y=c(1,1,1)) ) # Expect fine
check <- function(l){
df <- as.data.frame(l)
if(any(df == 0)){
if(any(rowSums(df) == df[,1]) ){
warning("this is a warning")
} else {
stop("this is an error")
}
}
}
check(A)
check(B)
check(C)
这篇关于从同一列表的元素中查找零位置的不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!