Order of operation with piping

前端 未结 1 1623
感情败类
感情败类 2020-12-07 02:08

My question is where does the piping operator of magrittr package %>% come in the order of operations?

I have a problem simmilar to the

相关标签:
1条回答
  • 2020-12-07 02:41

    The help page you are looking for is ?Syntax. (Don't feel bad for not being able to find this, it took me about six guesses at search keywords.) I'm going to quote its entire operator precedence table here:

    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)                      
    

    So magrittr's pipe operators, like all the operators of the form %whatever%, do indeed have precedence greater than multiply and divide but lower than exponentiation, and this is guaranteed by the language specification.


    Personally, I don't see the value in these operators. Why not just write

    round(df/rowSums(df), 3)
    

    which has the evaluation order you want, and is (IMNSHO) easier to read as well?

    0 讨论(0)
提交回复
热议问题