Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencig values in vector [duplicate]

Tags:

r

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
like image 471
Maxim Avatar asked Dec 08 '25 17:12

Maxim


1 Answers

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 -.

like image 168
PhillipD Avatar answered Dec 10 '25 12:12

PhillipD