Why doesn't the pipe operator %>%
work in the second example in the following code ?
library(magrittr)
# Works
job::job({install.packages("gtsummary")})
# Doesn't work
{install.packages("gtsummary")} %>% job::job()
# Error in code[[1]] : object of type 'symbol' is not subsettable
Is this because the piped object is an expression ? I'm not familiar with expressions in R
CodePudding user response:
Based on docs of magrittr library
Technical notes The magrittr pipe operators use non-standard evaluation
I think the problem comes from NSE algorithm in R
as a workaround you can use the native pip operator like
{install.packages("gtsummary")} |> job::job()
CodePudding user response:
The problem is that job::job
uses non-standard evaluation to grab the code you want to run without running it right away. A more basic examples of a function that does this is
nse <- function(x) {
as.character(substitute(x))
}
nse(hello)
# [1] "hello"
hello %>% nse
# [1] "."
So when you run nse(hello)
, note that hello
is not a variable but the function can use substitute()
to get the code for the value you pass to the function. So hello
is never evaluated, it's converted to a symbol.
When you use the magrittr
pipe, the value is not passed as itself. All values from the previous calculation are stored in a variable named "." so that's why we see that value when using the pipe operator. The job::job
function is expecting a code block, not just a single symbol .
hence you get the error.
The native |>
pipe operator works because it doesn't create the special value variable and it actually re-writes the code you wrote at the abstract syntax tree level. You can see this if you do
quote(hello %>% nse())
# hello %>% nse()
quote(hello |> nse())
# nse(hello)
The |>
operator actually re-writes the code so it doesn't exist.