Comparing two vectors in an if statement

前端 未结 3 1688
南方客
南方客 2020-12-06 04:15

I want put stop condition inside a function. The condition is that if first and second elements should match perfectly in order and length.

A <- c(\"A\",         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 04:44

    I'd probably use all.equal and which to get the information you want. It's not recommended to use all.equal in an if...else block for some reason, so we wrap it in isTRUE(). See ?all.equal for more:

    foo <- function(A,B){
      if (!isTRUE(all.equal(A,B))){
        mismatches <- paste(which(A != B), collapse = ",")
        stop("error the A and B does not match at the following columns: ", mismatches )
      } else {
        message("Yahtzee!")
      }
    }
    

    And in use:

    > foo(A,A)
    Yahtzee!
    > foo(A,B)
    Yahtzee!
    > foo(A,C)
    Error in foo(A, C) : 
      error the A and B does not match at the following columns: 2,4
    

提交回复
热议问题