5
2 + 2 %>% sqrt()
Because the result is not 2, but 3.4142?
5
2 + 2 %>% sqrt()
Because the result is not 2, but 3.4142?
6
This is because R follows the conventions of mathematics. First it is made the potentiation and its inverse operation, then multiplication and its inverse and, finally, addition and its inverse. Thus, 2 + 2 %>% sqrt()
means create the expression 2 + sqrt(2)
.
To obtain the desired result, it is necessary to explicitly inform that the addition has priority over potentiation (after all, taking the square root is equivalent to raising a number to 1/2 power) in this case. To do this, run (2 + 2) %>% sqrt()
5
In the R
the operator %>%
is called pipe, it will use the leftmost value to pass to the function, see what would be equivalent
library(magrittr)
print(2 + 2 %>% sqrt())
print(sqrt(2)+2)
Result of each print:
[1] 3.414214
[1] 3.414214
you must be imagining that he would pass 2+2
= 4 for sqrt, but that’s not what happens, it would be true if 2+2 were in parentheses (2+2)
print((2 + 2) %>% sqrt()) == 2
Browser other questions tagged r
You are not signed in. Login or sign up in order to post.