简体   繁体   English

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

[英]Order of operator precedence when using ":" (the colon)

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.我很困惑为什么表达式x[2:3]产生与x[1+1:3]不同的结果——第二个在末尾包含一个NA值。 What am I missing?我错过了什么?

Because the operator : has precedence over + so 1+1:3 is really 1+(1:3) (ie 2:4 ) and not 2:3 .因为运算符:优先于+所以1+1:3实际上是1+(1:3) (即2:4 )而不是2:3 Thus, to change the order of execution as defined operator precedence, use parentheses ()因此,要将执行顺序更改为定义的运算符优先级,请使用括号()

You can see the order of precedence of operators in the help file ?Syntax .您可以在帮助文件?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 %/% ) %any%特殊运算符(包括%%%/%
* / multiply, divide * /乘除
+ - (binary) add, subtract + - (二进制)加、减

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM