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", "B", "C", "D")
B <- A
C <- c("A", "C", "C", "E")
> A == B
[1] TRUE TRUE TRUE TRUE
This is good situation to go forward
> A == C
[1] TRUE FALSE TRUE FALSE
Since there is one false this condition to stop and output that the condition doesnot hold at 2 and 4 th column.
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
Am I missing something obvious ? Also I can output where error positions are ?
Are they identical?
> identical(A,C)
[1] FALSE
Which elements disagree:
> which(A != C)
[1] 2 4
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
Source: Stackoverflow.com