R Shiny checkboxInput 自动基于条件选择

huangapple go评论67阅读模式
英文:

R Shiny checkboxInput automatically selected based on ondition

问题

我在Shiny中有一个数据表,我想在其中插入一个带有复选框的列。到目前为止,这也没有问题。
然而,只有在满足特定条件时,这些复选框才应该自动选中。
我已经以鸢尾花数据集为例,并希望在`Sepal.Length`的值大于5时,在相应的复选框中设置一个标记。
使用我目前的方法,所有复选框都被选中,而不仅仅是符合条件的那些。
有人可以帮我解决这个问题吗?

英文:

I have a datatable in Shiny where I want to insert a column with checkboxes. This works also so far without problems.
However, these checkboxes should be selected automatically when a certain condition is met.
I have used the iris dataset as an example and would like to set a mark in the respective checkbox if the value in Sepal.Length is greater than 5.
With my current approach, all checkboxes are selected and unfortunately not only those that meet the condition.
Can anyone help me with my problem?

library(tidyverse)
library(shiny)
library(DT)

shinyInput<-function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), label=NULL, ...))
  }
  inputs
}

ui <- fluidPage(

  dataTableOutput("table")
  
)

server <- function(input, output) {

  table1 <- iris %>% 
    mutate(Check = shinyInput(checkboxInput, nrow(iris), 'check1', value = ifelse(Sepal.Length >= 5, TRUE, FALSE)))
  
  output$table <- renderDataTable({
    DT::datatable({table1},
                  escape = F)
  })
    
}

shinyApp(ui = ui, server = server)

Current output:

R Shiny checkboxInput 自动基于条件选择

Desired output:

R Shiny checkboxInput 自动基于条件选择

答案1

得分: 2

Your function shinyInput and the way you use it are not correct for multiple reasons.

Rather create the Check column as follows:

library(shiny)

shinyInput <- function(FUN, id, i, ...) {
  as.character(FUN(paste0(id, i), label = NULL, ...))
}

values <- iris$Sepal.Length >= 5
Check <- vapply(1:nrow(iris), function(i) {
  shinyInput(checkboxInput, "checkb", i, value = values[i])
}, FUN.VALUE = character(1))
英文:

Your function shinyInput and the way you use it are not correct for multiple reasons.

Rather create the Check column as follows:

library(shiny)

shinyInput&lt;-function(FUN, id, i, ...) {
  as.character(FUN(paste0(id, i), label=NULL, ...))
}

values &lt;- iris$Sepal.Length &gt;= 5
Check &lt;- vapply(1:nrow(iris), function(i) {
  shinyInput(checkboxInput, &quot;checkb&quot;, i, value = values[i])
}, FUN.VALUE = character(1))

huangapple
  • 本文由 发表于 2023年5月22日 17:57:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定