比较if语句中的两个向量 [英] Comparing two vectors in an if statement
问题描述
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(A和B在第2列不匹配和4} else {
cat(我很好)
}
警告信息:
如果(A!= B)(停止(错误1) )
条件长度> 1,只有第一个元素将被使用
我是否缺少一些明显的东西?还可以输出错误位置的位置?
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 $ b> all(D == E)
[1] TRUE
> all(length(D)== length(E))&& all(D == E)
[1] FALSE
length
的文档表示,它目前只输出长度为1的整数,但是这可能会在将来发生变化,所以这就是为什么我在中包含长度测试全部
。
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 ?
all
is one option:
> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")
> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE
But you may have to watch out for recycling:
> 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
The documentation for length
says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all
.
这篇关于比较if语句中的两个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!