2017-01-02 73 views
0

我有以下數據集時:無類錯誤創建一個閃亮的應用

Type <- c("Choice 1", "Choice 1", "Choice 1", "Choice 1", "Choice 1", 
    "Choice 1") 
Date <- c("02-02-2016", "02-03-2016", "02-04-2016", "02-05-2016", 
    "02-06-2016", "02-07-2016") 
Sentiment <- c(1, 2, 3, 4, 2, 3) 
df <- data.frame(Type, Date, Sentiment) 

現在我建立一個閃亮的應用程序,允許您過濾日期範圍,並選擇一個類型。那麼應該給你一個子集中所有情感值的直方圖。

因此,我創建了下面的閃亮代碼

df <- read.csv2("sample.csv", stringAsFactors = F) 
df$Date <- as.Date(df$Date, format = "%d-%m-%Y") 

library(shiny) 
ui <- fluidPage(tabsetPanel(
    #Sliders for the first panel 
    tabPanel("Tab 1",sidebarPanel(
     dateRangeInput("daterange1", "Date range:", 
        start = "2015-01-01", 
        end = "2015-12-31"), 
     selectInput("select", label = h3("Select box"), 
     choices = list("Choice 1" = 1,"Choice 2" = 2,"Choice 3" = 3), 
     selected = 1)), 
    mainPanel(plotOutput("coolplot"))), 

    #Sliders for the second panel 
    tabPanel("Tab 2", mainPanel("the results of tab2")) 
)) 
server <- function(input, output) { 
    filtered <- reactive({ 
    if (is.null(input$select)) { 
     return(NULL) } 
    df %>% filter(Date >= input$dateRangeInput[1], 
      Date <= input$dateRangeInput[2], 
      Type == input$select) 
    }) 

    output$coolplot <- renderPlot({ 
    ggplot(filtered(), aes(Sentiment)) + geom_histogram() 
    }) 
} 
shinyApp(ui = ui, server = server) 

然而,當我跑我得到以下錯誤:

incorrect length (0), expecting: 10 

,我應該怎樣做才能避免這個錯誤有什麼想法?

+0

'ggplot(過濾,AES(觀點))'應該是'ggplot(過濾(),AES(觀點) )',因爲'filtered'是一個**函數**返回一些東西。 – nrussell

+0

非常感謝nrussell!它帶來了這個bug。直到現在,我遇到了以下錯誤...(見編輯)。有什麼想法嗎? –

+0

'gincorrect長度(0),期望:10'是* *完全錯誤消息? – nrussell

回答

-1

這是一個典型的Shiny初始化錯誤。定義任何輸入之前,每個反應得到在開始執行時被調用一次,所以它們都是空在這一點上,這會導致各種不同的錯誤 - 而且很難診斷,如果你不知道這個問題的。

相當近一段時間,除了Shiny(req函數)之外,這個函數更容易解決。只需添加一個:

req(input$dateRangeInput); 

在你filter反應代碼在你的第一道防線。

並且記住在任何時候你有反應。事實上,你還需要其他地方有你直接在observeoutput代碼塊使用input$something結構,像在那裏你直接使用input$something

您需要閃亮的版本0.13.0或更好地爲這一點。如果你有閃亮的舊版本,你有以下形式的語句來保護您的代碼:

if (!is.null(input$something)){ 
    #your code that needs input$something 
} 
+0

爲什麼反對票? –