比较if语句中的两个向量

时间:2012-04-29 18:48:37

标签: r loops operators dataframe

我想把停止条件放在函数中。条件是如果第一和第二元素应按顺序和长度完美匹配。

A <- c("A", "B", "C", "D")
B <- A
C <- c("A", "C", "C", "E")

> A == B
[1] TRUE TRUE TRUE TRUE

这是前进的好方法

> A == C

[1]  TRUE  FALSE TRUE FALSE

由于有一个错误的条件停止并输出条件不在第2和第4列。

if (A != B) {
           stop("error the A and B does not match at column 2 and 4"} else {
            cat ("I am fine") 
                }
Warning message:
In if (A != B) (stop("error 1")) :
  the condition has length > 1 and only the first element will be used

我错过了一些明显的东西吗?我也可以输出错误位置的位置?

3 个答案:

答案 0 :(得分:52)

all是一个选项:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

但你可能需要注意回收:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

length的文档说它目前只输出一个长度为1的整数,但是它可能会在将来发生变化,这就是我在all中包装长度测试的原因。

答案 1 :(得分:25)

它们是否相同?

> identical(A,C)
[1] FALSE

哪些元素不同意:

> which(A != C)
[1] 2 4

答案 2 :(得分:7)

我可能会使用all.equalwhich来获取您想要的信息。由于某种原因,不建议在all.equal块中使用if...else,因此我们将其包装在isTRUE()中。有关详情,请参阅?all.equal

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!")
  }
}

并在使用中:

> 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
相关问题