Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two vectors in an if statement

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 ?

like image 840
jon Avatar asked Apr 29 '12 18:04

jon


People also ask

How do you compare two vectors?

A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.

How do you know if two vectors are identical R?

Check if Two Objects are Equal in R Programming – setequal() Function. setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not.

How do you check for equality in R?

The Equality Operator == For example, you can check whether two objects are equal (equality) by using a double equals sign == . We can see if the logical value of TRUE equals the logical value of TRUE by using this query TRUE == TRUE .


2 Answers

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.

like image 73
Aaron left Stack Overflow Avatar answered Sep 27 '22 23:09

Aaron left Stack Overflow


Are they identical?

> identical(A,C) [1] FALSE 

Which elements disagree:

> which(A != C) [1] 2 4 
like image 29
Matthew Lundberg Avatar answered Sep 27 '22 23:09

Matthew Lundberg