I have a vector and would like to extract element 3 and 4. Can you please help me understand what the logic is behind the code version without parenthesis? I appreciate your help.
a=c(1:5)
a[(2+1): 4] # with parenthesis, makes sense
[1] 3 4
a[ 2+1 : 4] # without parenthesis, what is the logic here?
[1] 3 4 5 NA
The : operator is evaluated before the + operator.
Consider
print(c(2+1:4))
This returns
[1] 3 4 5 6
Because a vector 1,2,3,4 is created, then all elements are added by 2.
R Operator Syntax and Precedence
gives an overview over the priority of R's operators. The sequence operator : comes before the arithmetic operators like + or -.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With