英文:
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:
Desired output:
答案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<-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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论