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
.
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)
我可能会使用all.equal
并which
获取您想要的信息.由于某些原因,不建议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!")
}
}
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)