Reputation: 728
I am having a pretty interesting problem related to computer's logical thinking in R that I would love to hear your inputs on whether my understanding is correct. Let's say I have 3 vectors A
, B
, C
of date-type strings in the format YYYY-MM-DD
(e.g. 2021-01-01
, 2021-12-31
). Assume length(A) = length(B)
, but length(C)
is at least ten-times larger, and all the elements in each vector A
, B
and C
are in increasing order.
Objective. I need to write an IF()
statement to check if any elements chosen from vector A
is less than some elements in vector C
, and if any element from vector B
is greater than some elements in vector C
(if Yes, I would do something). Can someone please help shed the light on whether the two IF
statements below are equivalent and indeed they helped me achieve this goal?
My attempt.
I initially tried this statement, but it did not quite work due to the unequal length of A
, B
vs C
if(any(A <= C & C <= B) {
do something here
}
After thinking for a while, I somehow think the above statement is equivalent to the following:
if(A <= max(C) & min(C) <= B){
do something here
}
Upvotes: 0
Views: 51
Reputation: 173803
An if
statement must operate on a length-1 logical test. If you have anything like A <= max(C)
then you are operating on a logical vector the same length as A
.
If you want to find out if any A
is less than any C
, and any B
is greater than any C
you could do:
if(min(A) < max(C) && min(C) < max(B))
Which is of course a length-one logical test.
Upvotes: 1