比较 if 语句中的两个向量 [英] Comparing two vectors in an if statement

查看:42
本文介绍了比较 if 语句中的两个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数中放置停止条件.条件是第一个和第二个元素是否应该在顺序和长度上完美匹配.

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

这是前进的好局面

> A == C

[1]  TRUE  FALSE TRUE FALSE

因为有一个错误,这个条件停止并输出该条件在第 2 和第 4 列不成立.

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 是一种选择:

> 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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆