配管操作顺序

Order of operation with piping

我的问题是 magrittr%>% 的管道运算符按操作顺序从哪里来?

我有一个类似以下的问题:

set.seed(10)
df <- data.frame(a=rnorm(3),b=rnorm(3),c=rnorm(3))
df/rowSums(df)  %>%  round(.,3) 

这导致以下非四舍五入的数字:

           a        b         c
1 -0.0121966 0.119878 0.8922125

为了得到四舍五入的数字,我需要将 df/rowSums(df) 放在方括号中。

我尝试了 +-*/^,从结果中我发现操作顺序如下关注:

  1. 指数
  2. 管道
  3. 乘除法
  4. 加减法

是这样吗,还是我对管道操作员的理解有问题?

您正在查找的帮助页面是 ?Syntax。 (不要因为找不到这个而难过,我花了大约六次猜测搜索关键字。)我将在这里引用它的整个运算符优先级 table:

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                       
   ‘< > <= >= == !=’  ordering and comparison                      
   ‘!’                negation                                     
   ‘&  &&’            and                                          
   ‘| ||’             or                                           
   ‘~’                as in formulae                               
   ‘-> ->>’           rightwards assignment                        
   ‘<- <<-’           assignment (right to left)                   
   ‘=’                assignment (right to left)                   
   ‘?’                help (unary and binary)                      

所以 magrittr 的管道运算符,如 all 形式的运算符 %whatever%,确实具有比乘法和除法更高但比求幂更低的优先级,这是由语言规范保证。


就我个人而言,我看不到这些运算符的价值。为什么不直接写

round(df/rowSums(df), 3)

哪个有你想要的评估顺序,并且(IMNSHO)也更容易阅读?