0

What's the best way to save a quosure so that it can be run on another session?

Consider the below, which uses the {rlang}'s quosure concept to quote an expression x+2 and captures its environment which is global and evaluates it to 4.

However, if you save the quosure and then start a fresh session, then eval_tidy no longer works because x may be undefined in the new environment.

My use-case is saving these expressions and running them in a separate session. What's the best way to save a quosure so that it can be run on another session? Is the only way to save the environment as well? This is not ideal as the environment may contain very large objects, so it's best if there is a lighter weight solution.

library(rlang)

x = 2

quo_x_plus_2 = quo(x + 2)


saveRDS(quo_x_plus_2, "plsdel.rds")

# quits R
q()


a = readRDS("plsdel.rds")

rlang::eval_tidy(a)
xiaodai
  • 14,889
  • 18
  • 76
  • 140

1 Answers1

1

It looks like this works if you create the quosure (and the variables it's referencing) within a function:

create_quo <- function() {
  x = 2
  quoted = quo(x + 2)
  quoted
}

quo_x_plus_2 <- create_quo()
# Has an environment attached rather than just
# referring to the global env
quo_get_env(quo_x_plus_2)

# Save, quit and reload as in the original question
saveRDS(quo_x_plus_2, "plsdel.rds")
# quits R
q()
a = readRDS("plsdel.rds")
rlang::eval_tidy(a)
Marius
  • 58,213
  • 16
  • 107
  • 105