In ggplot2, we extensively use the pattern <data> %||% <default value>, as in color <- data$color %||% "red". This works great when we know what column we want to look up in the data frame, but it fails if we want to do this with eval_tidy(), because eval_tidy() fails instead of returning NULL.
In my own code, I've worked around this by defining a function eval_default() which works like eval_tidy() but swaps in a default value if eval_tidy() fails:
https://github.com/wilkelab/cowplot/blob/06aeeb449ccc0fb343eb03c83111df7b171e73af/R/key_glyph.R#L145-L154
library(rlang)
eval_default <- function(x, data, default) {
force(default)
suppressWarnings(
tryCatch(
error = function(e) default,
eval_tidy(x, data)
)
)
}
data <- data.frame(x = 1)
eval_default(quo(x), data, NULL)
#> [1] 1
eval_default(quo(y), data, NULL)
#> NULL
Created on 2020-01-12 by the reprex package (v0.3.0)
Based on the conversation here, it seems I'm not the only one running into this issue, so maybe adding something like this function to rlang is justified.
One comment regarding my proposed implementation: I had to add suppressWarnings() to prevent a warning "restarting interrupted promise evaluation" that would sometimes pop up. I find this warning sufficiently disconcerting that I'm not sure I can just ignore it, but I don't know enough about the internals of R evaluation to understand what the warning means and whether it can be avoided instead of suppressed.
In ggplot2, we extensively use the pattern
<data> %||% <default value>, as incolor <- data$color %||% "red". This works great when we know what column we want to look up in the data frame, but it fails if we want to do this witheval_tidy(), becauseeval_tidy()fails instead of returningNULL.In my own code, I've worked around this by defining a function
eval_default()which works likeeval_tidy()but swaps in a default value ifeval_tidy()fails:https://github.com/wilkelab/cowplot/blob/06aeeb449ccc0fb343eb03c83111df7b171e73af/R/key_glyph.R#L145-L154
Created on 2020-01-12 by the reprex package (v0.3.0)
Based on the conversation here, it seems I'm not the only one running into this issue, so maybe adding something like this function to rlang is justified.
One comment regarding my proposed implementation: I had to add
suppressWarnings()to prevent a warning "restarting interrupted promise evaluation" that would sometimes pop up. I find this warning sufficiently disconcerting that I'm not sure I can just ignore it, but I don't know enough about the internals of R evaluation to understand what the warning means and whether it can be avoided instead of suppressed.