我正在尝试创建我的第一个闪亮的应用程序,但我面临着一个困难:在下面的可重现的例子中,我正在创建一个反应式的pickerInput (即只显示品牌提出一个等于访问者选择的输入的圆柱体)。
然后,我希望基于组合input_cyl
和picker_cny
(记住,picker_cny
依赖于input_cyl
)显示一个表,其中显示与组合input_cyl
和picker_cny
匹配的观察值的相关数据。
谢谢你的帮助!
df <- mtcars
df$brand <- rownames(mtcars)
df$brand <- gsub("([A-Za-z]+).*", "\\1", df$brand)
if (interactive()) {
library(shiny)
library(shinyWidgets)
library(shinythemes)
library(shinycssloaders)
# Define UI -----------------------------------------------
ui <- fluidPage(
# Application title
titlePanel("Reproducible Example"),
# Parameters
sidebarLayout(
sidebarPanel(
selectInput(inputId = "input_cyl", label = "Cyl",
choices = c("6", "4", "8")),
pickerInput(
inputId = "picker_cny",
label = "Select Company",
choices = paste0(unique(df$brand)),
options = list(`actions-box` = TRUE),
multiple = TRUE),
width = 2),
# Show Text
mainPanel(
tableOutput("table"),
width = 10)
))
# Define Server ------------------------------------------
server <- function(input, output, session) {
# Reactive pickerInput ---------------------------------
observeEvent(input$input_cyl, {
df_mod <- df[df$cyl == paste0(input$input_cyl), ]
# Method 1
disabled_choices <- !df$cyl %in% df_mod$cyl
updatePickerInput(session = session,
inputId = "picker_cny",
choices = paste0(unique(df$brand)),
choicesOpt = list(
disabled = disabled_choices,
style = ifelse(disabled_choices,
yes = "color: rgba(119, 119, 119, 0.5);",
no = "")
))
}, ignoreInit = TRUE)
output$table <- renderTable(df)
}
}
# Run the application
shinyApp(ui = ui, server = server)
发布于 2021-08-30 11:46:22
您需要一个反应式,它将处理输入中的更改,并在将数据帧提供给输出表之前对其进行子集。为此,您只需将此代码块添加到您的服务器:
data <- reactive({
if (length(input$picker_cny) > 0)
df[df$brand %in% input$picker_cny,]
else
df
})
并像这样更新output$table
:
output$table <- renderTable(data())
注:您可以随意移除reactive中的if else
,以获得以下结果:
data <- reactive({
df[df$brand %in% input$picker_cny,]
})
在这种情况下,唯一的区别是:当还没有输入任何输入时,您会显示全部还是不显示。这是一个品味问题。
https://stackoverflow.com/questions/68989464
复制相似问题