R - error combining tidy eval and tilde in plot_ly

Viewed 90

I'm having trouble understanding why the following code returns an error:

d <- tibble(a = 1:10, x = 1:10, y = 1:10)
f <- function(.data, expr) {
    plot_ly(.data %>% filter({{ expr }}), x = ~x, y = ~y) %>% add_markers()
}

f(d, a <= 5)

# "Error in as.list.environment(x, all.names = TRUE) : object 'a' not found"

But this runs as expected:

g <- function(.data, expr) {
    plot_ly(.data %>% filter({{ expr }})) %>% add_markers(x = ~x, y = ~y)
}

g(d, a <= 5)

It seems that using tidy eval and the plot_ly tilde formula in the same function call somehow causes a problem for the tidy eval? I'd like to understand why as to prevent future bugs. Is there a way to still use them in the same function call? I found this alternative:

h <- function(.data, expr) {
    rlang::eval_tidy(
        rlang::quo_squash(quo({
            plot_ly(.data %>% filter({{ expr }}), x = ~x, y = ~y) %>% add_markers()
        }))
    )
}

h(d, a <= 5)

but then I'd rather use my second form g() above

1 Answers

The second form you've linked to doesn't make much sense, I would avoid it.

If I rewrite your function like this it seems to work:

f <- function(.data, expr) {
  .data %>%
    filter({{ expr }}) %>%
    plot_ly(
      x = ~x,
      y = ~y
    ) %>%
    add_markers()
}

Not sure why though.

When I print a backtrace for the error in your post, I see that plotly is still using lazyeval under the hood, the predecessor of tidy eval. This is a bit suspicious, it might be worth filing a bug in the plotly repo.

Related