使用“:”(冒号)时运算符优先顺序

时间:2022-04-02 03:36:15

I am trying to extract values from a vector using numeric vectors expressed in two seemingly equivalent ways:

我试图使用以两种看似相同的方式表示的数字向量从向量中提取值:

x <- c(1,2,3)
x[2:3]
# [1] 2 3
x[1+1:3]
# [1]  2  3 NA

I am confused why the expression x[2:3] produces a result different from x[1+1:3] -- the second includes an NA value at the end. What am I missing?

我很困惑,为什么表达式x [2:3]产生的结果与x [1 + 1:3]不同 - 第二个包括结尾的NA值。我错过了什么?

1 个解决方案

#1


10  

Because the operator : has precedence over + so 1+1:3 is really 1+(1:3) (i. e. 2:4) and not 2:3. Thus, to change the order of execution as defined operator precedence, use parentheses ()

因为运算符:优先于+ 1所以1 + 1:3实际上是1+(1:3)(即2:4)而不是2:3。因此,要根据定义的运算符优先级更改执行顺序,请使用括号()

You can see the order of precedence of operators in the help file ?Syntax. Here is the relevant part:

您可以在帮助文件中查看运算符的优先顺序?语法。以下是相关部分:

The following unary and binary operators are defined. They are listed in precedence groups, from highest to lowest.
:: ::: access variables in a namespace
$ @ component / slot extraction
[ [[ indexing
^ exponentiation (right to left)
- + unary minus and plus
: sequence operator
%any% special operators (including %% and %/%)
* / multiply, divide
+ - (binary) add, subtract

定义了以下一元和二元运算符。它们列在优先级组中,从最高到最低。 ::::访问命名空间中的变量$ @ component / slot extract [[[indexing ^ exponentiation(从右到左) - +一元减号和加号:序列运算符%任何%特殊运算符(包括%%和%/%) * /乘,除+ - (二进制)加,减

#1


10  

Because the operator : has precedence over + so 1+1:3 is really 1+(1:3) (i. e. 2:4) and not 2:3. Thus, to change the order of execution as defined operator precedence, use parentheses ()

因为运算符:优先于+ 1所以1 + 1:3实际上是1+(1:3)(即2:4)而不是2:3。因此,要根据定义的运算符优先级更改执行顺序,请使用括号()

You can see the order of precedence of operators in the help file ?Syntax. Here is the relevant part:

您可以在帮助文件中查看运算符的优先顺序?语法。以下是相关部分:

The following unary and binary operators are defined. They are listed in precedence groups, from highest to lowest.
:: ::: access variables in a namespace
$ @ component / slot extraction
[ [[ indexing
^ exponentiation (right to left)
- + unary minus and plus
: sequence operator
%any% special operators (including %% and %/%)
* / multiply, divide
+ - (binary) add, subtract

定义了以下一元和二元运算符。它们列在优先级组中,从最高到最低。 ::::访问命名空间中的变量$ @ component / slot extract [[[indexing ^ exponentiation(从右到左) - +一元减号和加号:序列运算符%任何%特殊运算符(包括%%和%/%) * /乘,除+ - (二进制)加,减