The calculation is to square each elements, sum each column, divide by 5, then make the square root. Below is an example:
library(magrittr)
a <- matrix(data = c(1,2,100,200), nrow = 2, ncol = 2)
The data a
is:
[,1] [,2]
[1,] 1 100
[2,] 2 200
I tried two ways: the first one used the pipe.
(a^2 %>% colSums())/5 %>% sqrt() # Way 1
sqrt((a^2 %>% colSums())/5) # Way 2
Strangely, Way 1
and Way 2
produced different results.
The result of Way 1
is:
[1] 2.236068 22360.679775
The result of Way 2
is:
[1] 1 100
I expected the result of Way 2
. How did Way 1
happen? Why these different results occured?
CodePudding user response:
In way1, that result is (a^2 %>% colSums())/(5 %>% sqrt())
If you want way2's result in way1, you should use ((a^2 %>% colSums())/5) %>% sqrt()
CodePudding user response:
As @Park already pointed out, this is about operator precedence. I would advise a different solution, though. You are mixing pipes and conventional function calling and that is the underlying cause for your problem.
If you change the division to be another step in the pipe, everything is correct and consistent. You could do it like this
a^2 %>% colSums() %>% `/`(5) %>% sqrt()
That spares brackets, gives computation a natural order (reading from left to right) and the result is correct:
> a^2 %>% colSums() %>% `/`(5) %>% sqrt()
[1] 1 100
If you wanted to be totally consistent you could even make that
a %>%
`^`(2) %>%
colSums() %>%
`/`(5) %>%
sqrt()