當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R Syntax 運算符語法和優先級

R語言 Syntax 位於 base 包(package)。

說明

概要R語法並給出運算符的優先級。

細節

定義了以下一元和二元運算符。它們按優先級組列出,從最高到最低。

:: :::訪問命名空間中的變量
$ @元件/插槽提取
[ [[ indexing
^求冪(從右到左)
- +一元減號和加號
:序列運算符
%any% |>特殊運算符(包括 %%%/% )
* /乘、除
+ -(二進製)加、減
< > <= >= == !=排序和比較
! negation
& && and
| || or
~如公式中所示
-> ->>向右賦值
<- <<-賦值(從右到左)
=賦值(從右到左)
?幫助(一元和二進製)

在表達式中,除非另有說明,優先級相同的運算符從左到右進行計算。 (請注意,= 不一定是運算符。)

二元運算符 :::::$@ 要求名稱或字符串常量位於右側,前兩個也需要它們位於左側。

另請參閱部分中的鏈接涵蓋了基本語法的大多數其他方麵。

注意

之間存在顯著的優先級差異R和 S。特別是,在 S?與(二進製)具有相同的優先級+ -& && | ||具有同等優先權。

例子

## Logical AND ("&&") has higher precedence than OR ("||"):
TRUE || TRUE && FALSE   # is the same as
TRUE || (TRUE && FALSE) # and different from
(TRUE || TRUE) && FALSE

## Special operators have higher precedence than "!" (logical NOT).
## You can use this for %in% :
! 1:10 %in% c(2, 3, 5, 7) # same as !(1:10 %in% c(2, 3, 5, 7))
## but we strongly advise to use the "!( ... )" form in this case!


## '=' has lower precedence than '<-' ... so you should not mix them
##     (and '<-' is considered better style anyway):
## Not run: ## Consequently, this gives a ("non-catchable") error
 x <- y = 5  #->  Error in (x <- y) = 5 : ....

## End(Not run)

參考

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

也可以看看

Arithmetic , Comparison , Control , Extract , Logic , NumericConstants , Paren , Quotes , Reserved

“R 語言定義”手冊。

相關用法


注:本文由純淨天空篩選整理自R-devel大神的英文原創作品 Operator Syntax and Precedence。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。