使用purrr :: walk来设置多个事件观察者

时间:2018-05-28 10:48:04

标签: r shiny purrr

我有一组变量用作具有匹配函数的html元素的id(方便地命名为varname.helper()),每当在相应的html元素上触发事件时,我都希望调用它们

我尝试了以下内容:

server <- function(input, output, session) {
    observables <- c("foo1", "foo2", "foo3") # they are obviously much more than 3 vars...
    observables %>% walk(function(x) {
        observeEvent(quo(!!sym(paste0("input$", x))), quo(!!sym(paste0(x, ".helper"))(input)), handler.quoted=TRUE)
}

但它没有用。有什么想法吗?

1 个答案:

答案 0 :(得分:10)

你的问题从这里开始。整洁的评估不是解决这个问题的最佳方法。

    observeEvent(quo(!!sym(paste0("input$", x))), 
          quo(!!sym(paste0(x, ".helper"))(input)), handler.quoted=TRUE)

您想要(对吗?)获得input$foo1foo1.helper。使用您的代码,最终结果是此quo s,sym s和感叹号的群集。

首先,如果所有辅助变量都做同样的事情,为什么要创建许多名为foo1.helper的独立变量?将它们放在列表中会更有意义,因此您可以使用任何类型的循环/映射来使您的生活更轻松:

helpers <- list(foo1 = whatever..., foo2 = whatever...)

接下来,

quo(!!sym(paste0("input$", x)))

为您提供了一个具有特定用例的相当复杂的对象。而不是使用$,您最好使用双括号选择:

input[[x]]

这使您可以使用字符变量x根据名称从列表中选择项目。这些更容易使用。 $语法只是糖,不允许您轻松使用字符值。

总结一下:

observeEvent(input[[x]], quote(helpers[[x]](input)), handler.quoted = TRUE)

这是一个关于如何在代码中使用这些内容的简短示例。请注意,您必须在此处使用purrr::walk,因为您无法使用for循环。 for循环不能与观察者等特定方式一起很好地发挥作用。

所以你的代码会变成:

library(shiny)
library(purrr)

ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(
         actionButton("foo1", "Foo 1"),
         actionButton("foo2", "Foo 2")
      ),
      "Nothing here"
   )
)

server <- function(input, output) {
  helpers <- list(foo1 = quote(cat("foo 1; ")), foo2 = quote(cat("foo 2; ")))
  purrr::walk(c("foo1", "foo2"), ~ observeEvent(input[[.x]], 
        helpers[[.x]], handler.quoted = TRUE))
}

shinyApp(ui = ui, server = server)