Search code examples
rpipeoperator-precedencemagrittr

Understanding the correct use of magrittr pipe `%>%` syntax


I have a named numeric vector, where I am trying to divide each element by the sum of all elements. Then I want to use the signif function to round to the significant figure. This is easy enough doing it "old school", by computing the division and storing the variable, then subsequently using the stored variable to compute the significant figures. However, if I try to pipe the computation directly using the magrittrpipe operator (%>%), signif doesn't really do anything with the vector.

I am trying to understand what the distinction is, as I frequently run into issues with piping in combination with base R functions.

Here's an example, with the output I am getting:

> # My named vector
> v <-setNames(c(1:5), letters[1:5])

> # Dividing each element by the total sum and rounding to significant figures
> a <- v/sum(v)
> a <- signif(a, digits = 3)

> # Dividing each element by the total sum and piping directly to signif()
> b <- v/sum(v) %>% signif(digits = 3)

> a
> b

a: 0.0667   b 0.133   c 0.2   d 0.267   e 0.333

a: 0.0666666666666667 b: 0.133333333333333 c: 0.2 d: 0.266666666666667 e: 0.333333333333333


Solution

  • Following @akrun's hint: ?Syntax has

      ‘%any% |>’         special operators (including ‘%%’ and ‘%/%’) 
           ‘* /’              multiply, divide         
    

    showing that the pipe operator has higher precedence than /, so that your expression is effectively

    v/(sum(v) %>% signif(digits = 3))
    

    Adding parentheses will help: try

    (v/sum(v)) %>% signif(digits = 3)