后续行动:从同一列表的元素中查找零位置的不匹配 [英] Follow-up: Finding mismatches in zero positions from elements of the same list

查看:51
本文介绍了后续行动:从同一列表的元素中查找零位置的不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在跟踪此答案.我想创建一个 if()条件以捕获 list()的一个元素中的0值对于同一元素的第二个元素中的对应位置而言是否不为0 list()?

I'm following up on this answer. I want to create an 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).

问:尽管我预期 D 列表会出错,但我想知道为什么我的 if()不能捕获它,但是解决?

Q: Although I expect error for D list, I wonder why my if() doesn't catch it, is there a fix?

( 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


( D = list(x = c(0,1,1,0), y = c(2,1,0,0)) ) ## Expect error but my function doesn't catch it!



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) # Works fine
check(B) # Works fine
check(C) # Works fine

check(D) # NOT OK! Doesn't throw any error!

推荐答案

我们可以使用 xor

check <- function(l){
  
  if(any(unlist(l) == 0)){
    if(!any(do.call(xor, l)) ){
      warning("this is a warning")
    } else {
      stop("this is an error")
    }
  }
}

-测试

check(A)
#Error in check(A) : this is an error

check(B)
#Warning message:
#In check(B) : this is a warning
check(C)
check(D)
#Error in check(D) : this is an error


或将 rowSums 更改为

check <- function(l){
  df <- as.data.frame(l)
  if(any(df == 0)){
    if(!any(rowSums(df == 0) == 1) ){
      warning("this is a warning")
    } else {
      stop("this is an error")
    }
  }
  }
  
check(A)
#Error in check(A) : this is an error
check(B)
#Warning message:
#In check(B) : this is a warning
check(C)
check(D)
#Error in check(D) : this is an error
  

这篇关于后续行动:从同一列表的元素中查找零位置的不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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