In every language there are clauses to control the flow of execution, in R in particular I am talking about the if/else
, the while
and the repeat
. These are not very different from those that we can find in any other language, they evaluate a certain condition, depending on one Vedadero/Falso
of it, it will be the direction they take. But in R , there is a big little difference.
Being a purely vector language, there are no "scalar" data, although there are different types of data, this can only exist in a "container" (the most elementary is the vector), when we do it a = 1
in any language, we are assigning a space to store a single integer data, in R , it is the same, but with a subtle difference, an array of type integer is created, with a single element.
Now, with the evaluation of the conditions the same thing happens, it does not return a TRUE/FALSE
scalar, but rather a boolean vector, however the flow control, like the rest of the languages, is clearly "scalar", a single TRUE/FALSE
will determine the flow to follow So: How is this situation of needing a single piece of data for evaluation compatible in the language, when in reality the language does not have it?
We are going to use
if
as an example, but the operation is the same in any of the other clauses. In the first place, it never hurts to consult the documentation, and what we can notice is thatif/else
, hewhile
and herepeat
share the same help and what it says about thecondición
to be evaluated is very significant:Summarizing:
NA
Warning
Warning
aError
Let's see, with this, obviously there are no problems:
Now, what happens with a vector other element?
Exactly what is mentioned in the documentation, is allowed but only the first element of the vector is evaluated, and a
Warning
. Finally: Is there a way around thisWarning
? Yes, several, but it will depend on what we are looking for, let's see a little:If we want to check only the first element
If either element is TRUE
If all elements must be TRUE