【问题标题】:Capture non-equality of values in two elements of a list在列表的两个元素中捕获不相等的值
【发布时间】:2021-06-29 17:38:08
【问题描述】:

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

为了具体起见,我提供了 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 !

【问题讨论】:

    标签: r list function dataframe error-handling


    【解决方案1】:

    我们可以创建一个条件来检查list 中每个元素中的lengthunique 元素

    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)
    

    【讨论】:

    • 阿伦,HERE 是你让我问的问题。谢谢。
    • 你很好。
    猜你喜欢
    • 2017-05-11
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2019-12-05
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多