r-lib / carrier

Create standalone functions for remote execution
Other
50 stars 2 forks source link

Use of pipe operator (%>%) within crate() #10

Closed soylentOrange closed 1 year ago

soylentOrange commented 1 year ago

I'm heavily addicted to using pipes in R but I'm unable to use them within crated functions. My naive approach on just using magrittr::%>% with in a crated function obviously failed.

Would you consider giving a hint on how to use pipes correctly?

lionel- commented 1 year ago

Hello, you can pack it in the crate:

fn <- crate(`%>%` = magrittr::`%>%`, ~ .x %>% stats::var())
fn(1:10)
#> [1] 9.166667
lionel- commented 1 year ago

(or simply crate(`%>%` = `%>%`, ~ .x %>% stats::var()) if you have %>% in scope in your current environment, e.g. after a library(magrittr) or if imported in your package)

soylentOrange commented 1 year ago

You saved my day! Thanks for the prompt and helpful reply!

lionel- commented 1 year ago

hmm though I guess in that case you're importing the actual function, i.e. this thing:

> magrittr::`%>%`
function (lhs, rhs) 
{
    lhs <- substitute(lhs)
    rhs <- substitute(rhs)
    kind <- 1L
    env <- parent.frame()
    lazy <- TRUE
    .External2(magrittr_pipe)
}
<bytecode: 0x13a1ef738>
<environment: namespace:magrittr>

This should work in most cases but you might run into trouble if the environment you're sending the crate to doesn't have the same version of magrittr installed, because the internal code of %>% from your main process might be out of sync with the installed package on the target process. So a better way is to create an indirection:

crate(function(x) {
  `%>%` <- magrittr::`%>%`
  x %>% stats::var()
})