在 R 中的函数中使用 plot_ly 时如何维护因子

How to maintain factors when using plot_ly inside a function in R

提问人:Luther_Blissett 提问时间:8/6/2023 最后编辑:Luther_Blissett 更新时间:8/6/2023 访问量:21

问:

我正在尝试将条形图放入函数中,以便在需要时更改变量以绘制。代码在函数外部完美运行,但在函数内部的上下文中不起作用。 问题在于 barplot 不再将 x 变量视为 ,尽管它在 (测试后验证)中。plot_lyplot_lyfactorfactordata.frame

此外,如果能解释为什么我必须分别使用和解析上下文和上下文中的变量,我们将不胜感激。enquo(){{}}dplyrplotly

代码(注释是恢复因子的尝试):

library(plotly)
library(dplyr)
n <- 100
df <- data.frame(x = as.factor(sample(1:3, n, replace = T)), 
                   y = rnorm(n))

summary_plot <- function(df, var){
  quo_var <- enquo(var)
  
  data.frame(df %>%
               group_by({{var}}) %>%
               summarise(n = n())) %>%
  plot_ly(
    # x = ~as.factor(quo_var),
    # x = as.factor(~quo_var),
    x = ~quo_var,
    y = ~n,
    type = "bar"
  )
  
}

summary_plot(df, x)

plot_ly output

R 函数 dplyr 图解 r 因子

评论


答:

1赞 Prashant Bharadwaj 8/6/2023 #1

我无法重现您的错误。在使用数字或字母时,它对我来说也是一个因素。也许尝试更新您的 和包?plotly::ggplot::dplyr::

  • 需要引用函数参数中保存的变量,否则 group_by 和 plotly 将在数据集中查找调用的列并失败。将其传递给内部函数的正常方法是,但由于使用公式表示法在数据框中查找变量,因此您不需要 ,您也可以在没有enquo()var!!quo_varplot_ly()x = ~..!!x = quo_var~
  • 现在,作为 tidyverse 的一部分,它有一个快捷方式,可以通过直接用作方便的速记来避免工作流程group_by()enquo() .. !!.{{var}}

当你在函数参数中有数据变量(即一个包含 promise2 的 env 变量)时,你需要用双大括号括起来,比如 filter(df, {{ var }})。使用 dplyr/Indirect 部分进行编程

enter image description here

评论

0赞 Luther_Blissett 8/6/2023
这是答案:“您也可以在没有”的情况下使用”。谢谢。这些包和它们的语法太混乱了!x = quo_var~