ShinyApp错误:selectInput,数据子集化

时间:2015-10-13 08:50:54

标签: r data.table shiny subset shinydashboard

我正在创建闪亮的应用程序。我的目标是根据输入可视化一些数据切片。我对结果非常满意。 但是,我的应用程序在加载应用程序时有一些错误。在绘制图形和可视化输入之前,它会在屏幕上显示一些错误(您可以查看应用程序并查看问题)。

我相信,第一个问题是数据过滤。我无法弄清楚如何处理它以及问题是什么。我可以使用其他方法或其他包吗? (见output$Brand)。

Error in grep(pattern, levels(vector)) : invalid 'pattern' argument

创建selectInput时出现第二个错误。我希望在一个图中可视化特定类别的所有品牌,并且可以选择按品牌过滤数据。但是,我的方法效果不佳。有什么建议? (见output$Brand)。

Error in if (input$Brand == "All") { : argument is of length zero

另外,我附上您可以生成的代码。

您对如何简化代码有任何建议吗?

感谢您的帮助!

library(shiny)
library(shinydashboard)
library(data.table)
library(ggplot2)
library(grid)
library(scales)
library(ggthemes)



# Header -----------------------------------------------------------

header <- dashboardHeader(title="Dashboard")

# Sidebar --------------------------------------------------------------

sm <- sidebarMenu(
  menuItem(
    text="Graph1",
    tabName="Graph1",
    icon=icon("home")
    )
)

sidebar <- dashboardSidebar(sm)

# Body --------------------------------------------------

body <- dashboardBody(

# Layout  --------------------------------------------  

tabItems(
 tabItem(
  tabName="Graph1",

  fluidPage(
         fluidRow(

      box(
        title = "Inputs", status = "warning", width = 2, solidHeader = TRUE,

        uiOutput("Year"),
        uiOutput("Category"),
        uiOutput("Brand"),
        sliderInput("Finalas.Range", "Months:",
                    min = 1, max = 12, value = c(1,12)) 

         ),

      box(
        title = "Season", width = 10, status = "info", solidHeader = TRUE,

        plotOutput("Graph1")

   )  
  )
)
)
)
)

# Setup Shiny app UI components -------------------------------------------

ui <- dashboardPage(header, sidebar, body, skin="black")

# Setup Shiny app back-end components -------------------------------------

server <- function(input, output) {

# Generate data --------------------------------------

  set.seed(1992)
  n=99
  Year <- sample(2013:2015, n, replace = TRUE, prob = NULL)
  Month <- sample(1:12, n, replace = TRUE, prob = NULL)
  Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
  Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
  Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
  USD <- abs(rnorm(n))*100

  df <- data.frame(Year, Month, Category, Brand, USD)



  # Inputs --------------------------------------
  output$Year <- renderUI({
  selectInput("Year", 
            "Year:", 
            c(unique(as.character(df$Year))), selected = "2015")
  })


  output$Category <- renderUI({
    selectInput("Category", "Choose category:", 
            choices = c("Car","Bus", "Bike" ))
  })


  output$Brand <- renderUI({
    df2 <- (data.table(df))[like(df$Category,input$Category)]
    selectInput("Brand", 
            "Brand:", 
            c("All", unique(as.character(df2$Brand)))) 
  })


  # Plot --------------------------------

  output$Graph1 <- renderPlot({

df <- data.table(df)

      if (input$Brand == "All") {

        df <- df[like(df$Year, input$Year)]   
        df <- df[like(df$Category,input$Category)] 

        ggplot(df, aes(x=factor(Month,levels=1:12), y=USD, fill=Brand))+
          geom_bar(stat='identity')+
          scale_x_discrete('Month', breaks=factor(1:12), drop=FALSE)+
          scale_fill_gdocs(guide = guide_legend(title = "Brand"))

      } else {


        df <- df[like(df$Year, input$Year)]   
        df <- df[like(df$Category,input$Category)] 
        df <- df[which(df$Brand == input$Brand),]

        validate(
          need(sum(df$USD)>0, paste(input$Brand, "was inactive in Year:",input$Year))
          )

        ggplot(df, aes(x=factor(Month,levels=1:12), y=USD, fill=Brand))+
          geom_bar(stat='identity')+
          scale_x_discrete('Month', breaks=factor(1:12), drop=FALSE) 
      }

  })

# ----------------------------------------------------------------------------- 

}

# Render Shiny app --------------------------------------------------------

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:2)

以下内容应消除这些错误:对于#1,like中的datatable函数会发出错误,因此我将其更改为%in%。对于#2,您有null作为默认值,因此请使用if语句来处理

rm(list = ls())
library(shiny)
library(shinydashboard)
library(data.table)
library(ggplot2)
library(grid)
library(scales)
library(ggthemes)


# Header -----------------------------------------------------------

header <- dashboardHeader(title="Dashboard")

# Sidebar --------------------------------------------------------------

sm <- sidebarMenu(
  menuItem(
    text="Graph1",
    tabName="Graph1",
    icon=icon("home")
  )
)

sidebar <- dashboardSidebar(sm)

# Body --------------------------------------------------

body <- dashboardBody(

  # Layout  --------------------------------------------  

  tabItems(
    tabItem(
      tabName="Graph1",

      fluidPage(
        fluidRow(

          box(
            title = "Inputs", status = "warning", width = 2, solidHeader = TRUE,

            uiOutput("Year"),
            uiOutput("Category"),
            uiOutput("Brand"),
            sliderInput("Finalas.Range", "Months:",
                        min = 1, max = 12, value = c(1,12)) 

          ),

          box(
            title = "Season", width = 10, status = "info", solidHeader = TRUE,

            plotOutput("Graph1")

          )  
        )
      )
    )
  )
)

# Setup Shiny app UI components -------------------------------------------

ui <- dashboardPage(header, sidebar, body, skin="black")

# Setup Shiny app back-end components -------------------------------------

server <- function(input, output) {

  # Generate data --------------------------------------

  set.seed(1992)
  n=99
  Year <- sample(2013:2015, n, replace = TRUE, prob = NULL)
  Month <- sample(1:12, n, replace = TRUE, prob = NULL)
  Category <- sample(c("Car", "Bus", "Bike"), n, replace = TRUE, prob = NULL)
  Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
  Brand <- paste0(Brand, sample(1:14, n, replace = TRUE, prob = NULL))
  USD <- abs(rnorm(n))*100

  df <- data.frame(Year, Month, Category, Brand, USD)



  # Inputs --------------------------------------
  output$Year <- renderUI({
    selectInput("Year", 
                "Year:", 
                c(unique(as.character(df$Year))), selected = "2015")
  })


  output$Category <- renderUI({
    selectInput("Category", "Choose category:", 
                choices = c("Car","Bus", "Bike" ))
  })


  output$Brand <- renderUI({


    # first error
    #df2 <- (data.table(df))[like(df$Category,input$Category)]

    df2 <- df[df$Category %in% input$Category,]


    selectInput("Brand", 
                "Brand:", 
                c("All", unique(as.character(df2$Brand)))) 
  })


  # Plot --------------------------------

  output$Graph1 <- renderPlot({

    df <- data.table(df)

    if(is.null(input$Brand) || is.na(input$Brand)){return()}

    else if (input$Brand == "All") {

      df <- df[like(df$Year, input$Year)]   
      df <- df[like(df$Category,input$Category)] 

      ggplot(df, aes(x=factor(Month,levels=1:12), y=USD, fill=Brand))+
        geom_bar(stat='identity')+
        scale_x_discrete('Month', breaks=factor(1:12), drop=FALSE)+
        scale_fill_gdocs(guide = guide_legend(title = "Brand"))

    } else {


      df <- df[like(df$Year, input$Year)]   
      df <- df[like(df$Category,input$Category)] 
      df <- df[which(df$Brand == input$Brand),]

      validate(
        need(sum(df$USD)>0, paste(input$Brand, "was inactive in Year:",input$Year))
      )

      ggplot(df, aes(x=factor(Month,levels=1:12), y=USD, fill=Brand))+
        geom_bar(stat='identity')+
        scale_x_discrete('Month', breaks=factor(1:12), drop=FALSE) 
    }

  })

  # ----------------------------------------------------------------------------- 

}

# Render Shiny app --------------------------------------------------------

shinyApp(ui, server)