我正在尝试创建一个有光泽的应用程序。在这个特定的应用程序中,我有一组单选按钮,其中选择一个将在下面显示一组选项,如“复选框”,而选择另一个单选按钮将选择其他选项。请在下面找到用户界面和服务器代码。
library(shiny)
library(shinydashboard)
library(shinyWidgets)
d <-
data.frame(
year = c(1995, 1995, 1995, 1996, 1996, 1996, 1997, 1997, 1997),
Product_Name = c(
"Table",
"Chair",
"Bed",
"Table",
"Chair",
"Bed",
"Table",
"Chair",
"Bed"
),
Product_desc = c("X", "X", "X", "Y", "Y", "Y", "Z", "Z", "Z"),
Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
)
ui <- shinyUI(fluidPage(
useShinydashboard(),
tabPanel(
"Plot",
sidebarLayout(
sidebarPanel(
radioButtons(
"Choose",
"Choose One",
c("Year" = "p", "Numbers" = "l")
),
uiOutput('checkbox'),
#width = 2,
position = "bottom"),
mainPanel(uiOutput("graph"))
)
)
))
server <- function(input, output, session) {
output$graph <- renderUI({
# create tabPanel with datatable in it
req(input$year)
tabPanel("Plots",
fluidRow(lapply(as.list(paste0("plot", seq_along(input$year))), plotOutput)))
})
output$checkbox <- renderUI({
if (input$Choose == "p") {
checkboxGroupInput("Cross",
"Year",
choices = (unique(d$year)))
} else{
checkboxGroupInput("Cross_1",
"Numbers",
choices = c("1","2","3"))
}
})
}
shinyApp(ui, server)
现在,我面临的挑战是,当我选择“年份”单选按钮时,年份值将显示为复选框,而当我选择复选框时,相应的图形将显示在主面板中(我没有给出代码在这里)。现在,当我选择“数字”单选按钮时,将显示正确的复选框选项。但是当我回到“年”单选按钮时。已经选择的复选框值不会保留,因此用户需要再次选中复选框以获取相应的图形。
即使选择了另一个单选按钮,也请向我建议如何保留复选框中的值。还请注意,每个单选按钮下方的复选框选项将根据用户在上一个选项卡中选择的选项而更改。因此,我使用观察功能来获取相应的复选框。
我建议显示/隐藏复选框,而不要使用renderUI
。这样,即使未显示,它们也将保留其设置。
shinyjs
是一个受欢迎的软件包,可以为我们完成此任务。我已经根据上述代码创建了一个最小的示例,以展示其实际效果:
library(shiny)
library(shinyjs)
ui <- shinyUI(fluidPage(
useShinyjs(),
radioButtons("radio_choose", "Choose One", choices = c("Year", "Numbers")),
checkboxGroupInput("checkbox_years", "Year", choices = c(1995, 1996, 1997, 1997)),
checkboxGroupInput("checkbox_numbers", "Numbers", choices = c(1, 2, 3))
))
server <- function(input, output, session) {
#Observe the radio buttons (runs when the radio button changes)
observeEvent(input$radio_choose, {
if(input$radio_choose == "Year") {
shinyjs::show("checkbox_years")
shinyjs::hide("checkbox_numbers")
}
if(input$radio_choose == "Numbers") {
shinyjs::hide("checkbox_years")
shinyjs::show("checkbox_numbers")
}
})
}
shinyApp(ui, server)