首页 > 解决方案 > 在列表的两个元素中捕获不相等的值

问题描述

我想创建if()条件来捕获xa 元素中的值list()不完全相同ya 元素中的值list()不完全相同两种情况一起出现的情况。

具体而言,我提供了 4 个列表以及下面的预期警告。

这在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 !

标签: rlistfunctiondataframeerror-handling

解决方案


我们可以创建一个条件lengthunique检查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)

推荐阅读