如何根据带有闪亮元素的 R Markdown 文档中的条件禁用按钮?

How to disable button based on a condition in a R Markdown document with shiny elements?

假设我们有一组 8 个复选框(8 个字母)和一个打印所有选中复选框标签的操作按钮。我想做的是,根据条件启用和禁用操作按钮的状态。条件是,如果选中的复选框数在 2 到 5 之间,则应启用该按钮,否则禁用。为了更改按钮的状态,我想使用 shinyjs 包中的 enabledisabletoggleState 函数。当按钮启用时,我将能够触发一个事件来打印所选项目的数量。 这是我到目前为止尝试过的方法:

---
title: "Disable Button"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(shinyjs)
library(shiny)
```

```{r, echo=FALSE}
checkboxGroupInput("param_group", label = h3("Letters"), 
    choices = LETTERS[1:8])

actionButton('action', "Print")

result<-reactive({
  length(input$param_group)
})

observe({
  if(result()>1 & result()<=5)
    enable("action")
  else
    disable("action")
})

txt<-eventReactive(input$action,{
    cat("Number of letters selected: ",length(input$param_group))
})

renderPrint({
  txt()
})
```

我花了一些时间才找到它,但你必须启用 shinyjs 才能明确使用 R-markdown,在这种情况下它需要以不同的方式设置其 javascript。

您可以通过调用:useShinyjs(rmd=T) 在您使用它的块中执行此操作。

---
title: "Disable Button"
runtime: shiny
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(shinyjs)
library(shiny)
```

```{r, echo=FALSE}
useShinyjs(rmd=T)

checkboxGroupInput("param_group", label = h3("Letters"), 
                   choices = LETTERS[1:8])

actionButton('action', "Print")


result<-reactive({
  length(input$param_group)
})

observe({
  useShinyjs()
  if(result()>1 & result()<=5){
    enable("action")
  } else {
    disable("action")
  }
})

txt<-eventReactive(input$action,{
  cat("Number of letters selected: ",length(input$param_group))
})

renderPrint({
  txt()
})

屏幕截图: