【问题标题】:radioButtons() input as a condition to filter a data frame in Shiny, doesn't seem to workradioButtons() 输入作为在 Shiny 中过滤数据框的条件,似乎不起作用
【发布时间】:2020-12-03 22:28:46
【问题描述】:

使用来自ggplot2midwest 数据框:

# (in app_ui.r)

poverty_sidebar <- sidebarPanel(
  radioButtons(
    inputId = "state",
    label = "State",
    choices = list("IL" = 1, "IN" = 2, "MI" = 3, "OH" = 4, "WI" = 5),
    selected = 1
  ))

poverty_plot <- mainPanel(
  plotOutput(
    outputId = "poverty_plot"
  )
)

# (in app_server.r)

server <- function(input, output) {
  
  output$poverty_plot <- renderPlot({
    
    filtered <- filter(midwest, state == input$state)
    
    plot <- ggplot(data = filtered) +
      geom_col(x = county, y = poppovertyknown)
    
    return(plot)
  })
  

似乎不起作用,给我一个“找不到对象county”错​​误。是在做filter(midwest, state == input$state) 错误的方法吗?还是错误出在我的单选按钮上?

【问题讨论】:

  • 试试choices = list("IL" , "IN" , "MI" , "OH" , "WI" )
  • 给我同样的错误:“找不到对象county

标签: r ggplot2 dplyr shiny


【解决方案1】:

所以提供的代码很接近,你犯了两个错误

  1. choices 不需要映射到数字
  2. x = county, y = poppovertyknown 应该在 aesgeom_col 所以 aes(x = county, y = poppovertyknown)

因此最终的工作代码将是(注意,我已将分配添加到 ui 以使其在单个文件中工作,并调用 shinyApp(ui, server)),

library(shiny)
library(dplyr)
library(ggplot2)


poverty_sidebar <- sidebarPanel(
  radioButtons(
    inputId = "state",
    label = "State",
    choices = list("IL", "IN", "MI", "OH", "WI"), # remove mapping to integers
    selected = "IL"
  ))

poverty_plot <- mainPanel(
  plotOutput(
    outputId = "poverty_plot"
  )
)

ui <- 
  fluidPage(
    poverty_sidebar,
    poverty_plot
  )
  

# (in app_server.r)

server <- function(input, output) {
  
  output$poverty_plot <- renderPlot({
    
    filtered <- filter(midwest, state == input$state)
    print(filtered)
    print(input$state)
    filtered0 <<- filtered
    plot <- 
      filtered %>% 
      ggplot() +
      geom_col(aes(x = county, y = poppovertyknown)) # used aes()
    
    return(plot)
  })
  
}

shinyApp(ui, server)

【讨论】:

  • 毁掉一切的小错误。非常感谢!
猜你喜欢
  • 2012-06-11
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多