比较if语句中的两个向量

jon*_*jon 36 loops r operators dataframe

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

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

> A == B
[1] TRUE TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)

这是前进的好局面

> A == C

[1]  TRUE  FALSE TRUE FALSE
Run Code Online (Sandbox Code Playgroud)

由于有一个错误的条件停止并输出该条件不在第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
Run Code Online (Sandbox Code Playgroud)

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

Aar*_*ica 57

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
Run Code Online (Sandbox Code Playgroud)

但您可能需要注意回收:

> 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
Run Code Online (Sandbox Code Playgroud)

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

  • 你对回收的谨慎是你应该使用`isTRUE(all.equal(D,E))`的原因. (6认同)

Mat*_*erg 26

它们是一样的吗?

> identical(A,C)
[1] FALSE
Run Code Online (Sandbox Code Playgroud)

哪些元素不同意:

> which(A != C)
[1] 2 4
Run Code Online (Sandbox Code Playgroud)

  • `same`也比较属性,这可能是也可能不是. (6认同)
  • 这里没有属性,但这是一个重要的点。谢谢。 (2认同)

Cha*_*ase 7

我可能会使用all.equalwhich获取您想要的信息.由于某些原因,不建议all.equalif...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!")
  }
}
Run Code Online (Sandbox Code Playgroud)

在使用中:

> 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
Run Code Online (Sandbox Code Playgroud)

  • 原因是,当它们不相等时,它不会返回“FALSE”,而是返回它们差异的描述。 (2认同)