R语言 如何简化简化代码?

ctrmrzij  于 2023-01-22  发布在  其他
关注(0)|答案(2)|浏览(200)

我想知道我怎样才能简化下面的代码?

observeEvent(input$structure_explorer_refresh, {
    shinyjs::reset("structure_explorer_form")
  })
  observeEvent(input$property_refresh, {
    shinyjs::reset("property_form")
  })
  observeEvent(input$structure_activity_refresh, {
    shinyjs::reset("structure_activity_form")
  })  
  observeEvent(input$structure_target_refresh, {
    shinyjs::reset("structure_target_form")
  })    
  observeEvent(input$target_id_refresh, {
    shinyjs::reset("target_id_form")
  }) 
  observeEvent(input$target_activity_refresh, {
    shinyjs::reset("target_activity_form")
  })  
  observeEvent(input$drug_target_refresh, {
    shinyjs::reset("drug_target_form")
  })    
  observeEvent(input$drug_info_refresh, {
    shinyjs::reset("drug_info_form")
  })  
  observeEvent(input$assay_id_refresh, {
    shinyjs::reset("assay_id_form")
  })

我已经尝试应用这个suggestion,但我无法使它工作。

de90aj5v

de90aj5v1#

也许像这样:

xxx <- c(
  "structure_explorer_",
  "property_",
  ......
)

for(x in xxx) {
  observeEvent(input[[paste0(x, "refresh")]], {
    shinyjs::reset(paste0(x, "form"))
  })
}
oaxa6hgo

oaxa6hgo2#

我们可以创建一个没有ui的模块,然后在执行循环时将输入的名称作为参数传递。

reset_server <- function(id, refresh_button, refresh_name) {
  moduleServer(
    id,
    function(input, output, session) {
      ns <- session$ns
      observeEvent(refresh_button(), {
        shinyjs::reset(refresh_name, asis = TRUE)
      })
    }
  )
}

示例代码:

ui <- fluidPage(
  shinyjs::useShinyjs(),
  c("assay_id_refresh", "drug_info_refresh", "drug_target_refresh") |>
    purrr::map(\(x) actionButton(inputId = x, label = x)),
  c("assay_id_form", "drug_info_form", "drug_target_form") |>
    purrr::map(\(x) selectInput(
      inputId  = x,
      label    = x,
      choices  = 1:10,
      multiple = TRUE
    ))
)

server <- function(input, output, session) {
  purrr::walk2(
    .x = c("assay_id_refresh", "drug_info_refresh", "drug_target_refresh"),
    .y = c("assay_id_form", "drug_info_form", "drug_target_form"),
    .f = ~ reset_server(
      id             = .x,
      refresh_button = reactive(input[[.x]]),
      refresh_name   = .y
    )
  )
}

shinyApp(ui, server)

相关问题