I am unable to determine how to use (some ?) numerical formulas with magrittr
. Here is a particular case:
library(magrittr)
y = c( complex(1, 1.0,2.0), complex(1, 3.0,4.0))
ymagn = y %>% sqrt(Re(.)**2 + Im(.)**2)
Which results in
Error in sqrt(., Re(.)^2 + Im(.)^2) : 2 arguments passed to 'sqrt' which requires 1
Here is one approach you can use:
ymagn = y %>% {sqrt(Re(.)**2 + Im(.)**2)}
[1] 2.236068 5.000000
The reason your version does not work is because by default the %>%
operator provides the output of the left hand side (LHS) as the first argument of the right hand side (RHS).
Under the default circumstances, if you provide .
again, in addition to providing it as the first argument, the pipe operator will provide the output in place of .
. As you can read in help(`%>%`,"magrittr")
, the package authors intend you to use this functionality in this type of way:
iris %>% subset(., 1:nrow(.) %% 2 == 0)
Without the brackets, the code you attempted is evaluated in this way:
ymagn = y %>% sqrt(.,Re(.)**2 + Im(.)**2)
This explains the error reporting 2 arguments.
Using the brackets is called a lambda expression. From help(`%>%`,"magrittr")
:
Using lambda expressions with %>%
Each rhs is essentially a one-expression body of a unary function. Therefore defining lambdas in magrittr is very natural, and as the definitions of regular functions: if more than a single expression is needed one encloses the body in a pair of braces, { rhs }. However, note that within braces there are no "first-argument rule": it will be exactly like writing a unary function where the argument name is "." (the dot).