1
使用Shiny,我試圖根據用戶輸入過濾數據幀,然後顯示過濾的數據幀。我努力尋找一種策略,在適用的情況下,我可以不過濾數據幀並顯示未過濾的數據幀。我搜索堆棧溢出尋求幫助,並發現這個相似的問題R - Shiny Filter for 'All' values。我試圖實施Kristoffer Winther Balling推薦的解決方案,但未成功。當我選擇「無選擇」選項時,會顯示一個空的表格而不是未過濾的表格。基於Shiny用戶輸入過濾數據幀,等於「沒有選擇」= NA
library(shiny)
library(tidyverse)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "cut", label = "Select Cut",
choiceNames = c(levels(as.factor(diamonds$cut)), "None Selected"),
choiceValues = c(levels(as.factor(diamonds$cut)), NA))
),
mainPanel(tableOutput("diamonds_filtered"))
)
)
server <- function(input, output) {
output$diamonds_filtered <- renderTable({
diamonds_filtered <- diamonds
if (!is.na(input$cut)) {
diamonds_filtered <- filter(diamonds_filtered, cut == input$cut)
}
head(diamonds_filtered)
})
}
shinyApp(ui, server)
對用戶輸入不等於NA的過濾按預期工作。 Proper filtering
然而,當輸入爲「無選擇」且值爲NA時,未顯示未過濾的數據幀。 improper filtering
對於我可能會做錯的任何建議都非常感謝。
使用'if(input $ cut!=「」){...'而不是 – HubertL
@HubertL非常感謝您的建議!一旦我將「None Selected」選項的值修改爲=「」,並按照您的建議更改了我的if語句,我就得到了所需的輸出結果。謝謝!!我已經用你的建議回答了下面的問題。 –
如果你保留NA,它應該可以工作 – HubertL