r - 结合公式和整洁的评估( plotly )

标签 r plotly rlang

我很难理解这一点。

下面让我以“整洁”的方式过滤我的 data.frame,并使用 plotly 绘制绘图。在这种情况下,我使用 plotly 的基于公式的 API 来说明要使用数据框的哪些列:

library(plotly)

tidy_filter = function(data, x) {
  x = enquo(x)
  filter(data, !!x > 5)
}

mtcars %>% 
  tidy_filter(wt) %>% 
  plot_ly(x = ~wt, y = ~wt)

我可以将它包装在一个函数中以获得相同的结果:

tidy_ply = function(data, x) {
  x = enquo(x)
  data = filter(data, !!x > 5)
  plot_ly(data, x = x, y = x)
}

tidy_ply(mtcars, wt)

现在:

  1. 我假设 enquo(x) 在这种情况下至少部分等同于 ~wt 因为它似乎是这样工作的。但它们是两个不同的东西(quosure VS formula)。它们之间有什么关系,为什么会出现上述问题?

  2. plotly 的公式API 的优点是,如果我想操作输入值,我可以做类似~wt/2 的事情。但在上面,执行 plot_ly(data, x = x, y = x/2) 会产生错误。有什么办法可以做到这一点吗?

我想普遍的问题是如何最好地将 tidy eval 方法与 plotly 的公式方法结合起来?

最佳答案

从这里answer通过@alistaire:

The plotly R package was created a little before rlang, and has its own non-standard evaluation (NSE) system, that as far as I can tell is mostly only documented in the examples.

When NSE systems go sideways, the quickest way to get it to work is to rewrite all the code dynamically and then evaluate it. Here, wrap the whole plotly pipeline in quo with !! substitution wherever you like, then call quo_squash on it to collapse it to a single expression (instead of nested quosures), and then call eval_tidy on the whole lot to actually run it.

In plotly, ~ is used to refer to a column in the dataset to be visualized (@cpsievert).

在您的示例中,x 是一个 quosure,因此您必须在应用任何基本运算符之前首先取消对它的引用。这就是错误消息告诉您的内容:

Error: Base operators are not defined for quosures.
Do you need to unquote the quosure?

  # Bad:
  myquosure / rhs

  # Good:
  !!myquosure / rhs

这是一个可行的解决方案:

library(rlang)
library(plotly)

tidy_ply2 <- function(data, x) {
  x = enquo(x)
  print(x)
  
  data = filter(data, !!x > 5)
  
  # https://rlang.r-lib.org/reference/quasiquotation.html
  cat('\nUse qq_show() to debug the effect of unquoting operators\n')
  qq_show(plot_ly(data, x = ~!!x, y = ~!!x/2))
  
  # `base::eval` works too
  eval_tidy(
    quo_squash(
      quo({
        plot_ly(data, x = ~!!x, y = ~!!x/2)
      })
    )
  )
}

tidy_ply2(mtcars, wt)
#> <quosure>
#> expr: ^wt
#> env:  global
#> 
#> Use qq_show() to debug the effect of unquoting operators
#> plot_ly(data, x = ~^wt, y = ~(^wt) / 2)
#> 

reprex package 创建于 2019-04-03 (v0.2.1.9000)

关于r - 结合公式和整洁的评估( plotly ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55505599/

相关文章:

r - dplyr 的多重滞后

r - 如何更改 heatmap.2 中的色键高度

r - 在 R 中修改 data.table 中的值

r - Knitr 在 R 代码中转义 latex 特殊字符(例如,〜,$)

python - plotly.figure_factory.create_annotated_heatmap 没有正确显示带有轴标签的图形

python - Plotly Dash - 如何设置自动颜色而不是所有东西都用蓝色

r - 创建 dplyr 语句,稍后在 R 中进行评估

r - 按位置排列的列表元素的平均值

javascript - R plotly : how to observe whether a trace is hidden or shown through legend clicks with multiple plots

data.table - 使用 eval(substitute()) 传递给函数时取消引用参数