Home > Enterprise >  Does piping affect operations with sqrt function?
Does piping affect operations with sqrt function?

Time:07-12

I was doing some calculations and I noticed that when I add pipes it outputs a wrong result. It is the first time I encounter this and I would like to know why it happens to avoid this situation in the future.

# Making the operations separately gives the correct result.
0.58*(1-0.58) # 0.2436
sqrt(0.2436) # 0.4935585

# Adding all calculations in the same line works.
sqrt(0.58*(1-0.58)) # 0.4935585

# Use %>% doesn't give the right result.
0.58*(1-0.58) %>% sqrt() # 0.375883

# The issue doesn't happen when in a df or tibble
tibble(a = c(0.2436)) %>% 
  mutate(b = sqrt(a))
    #  A tibble: 1 × 2
    #      a     b
    #   <dbl> <dbl>
    # 1 0.244 0.494

Thank you,

CodePudding user response:

If you look at ?Syntax, you'll see that subtraction is higher precedence than pipes, and pipes are higher precedence than multiplication.

So in this expression:

0.58 * (1 - 0.58) %>% sqrt()

1 - 0.58 is evaluated to 0.42. Then 0.42 is piped to sqrt(). Then the result is multiplied by 0.58.

sqrt(0.42) * 0.58
[1] 0.375883

You can avoid it by wrapping the left-hand side in parentheses:

(0.58*(1-0.58)) %>% sqrt(.)
[1] 0.4935585

CodePudding user response:

It's happening due to operator precedence. And as always, using parenthesis can save from such unexpected things.

library(magrittr)

(0.58*(1-0.58)) %>% sqrt()
#> [1] 0.4935585


# here multiplication is evaluated after piping.
0.58*(1-0.58) %>% sqrt()
#> [1] 0.375883

# so the above is same as doing this
((1-0.58) %>% sqrt()) * 0.58
#> [1] 0.375883

Created on 2022-07-12 by the reprex package (v2.0.1)

  • Related