使用“:"时,运算符优先级顺序(冒号) [英] Order of operator precedence when using ":" (the colon)

查看:318
本文介绍了使用“:"时,运算符优先级顺序(冒号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以两种看似等效的方式表示的数值向量从向量中提取值:

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

我很困惑为什么表达式x[2:3]产生与x[1+1: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?

推荐答案

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

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 ()

您可以在帮助文件?Syntax中看到运算符的优先顺序.这是相关的部分:

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

定义了以下一元和二进制运算符.它们按从高到低的顺序排列在优先级组中.
:: :::访问命名空间中的变量
$ @组件/插槽提取
[ [[索引
^求幂(从右到左)
- +一元减号和加号
:序列运算符
%any%特殊运算符(包括%%%/%)
* /乘除除
+ -(二进制)加,减

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

这篇关于使用“:"时,运算符优先级顺序(冒号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆