呈浅黄色-R-文字会丢失数据,导致错误

时间:2018-11-04 22:50:12

标签: r shiny plotly

我正在制作一个闪亮的应用程序,它可以过滤并汇总大量数据。 它在大多数情况下都起作用。但是我受法律的限制,限制了图表中显示的内容,因此我将所有低于5的内容过滤掉(如代码所示)。这导致某些变量被呈现为零,并且因为我在add_trace中包含了引发的文本我遇到一个错误(列text的长度必须为0,而不是1)。 我试图找到一种方法,如果情节为空则获取文本输出,或者防止错误显示。

如果输出抛出错误,我还可以渲染其他内容(自定义消息),这也可能对我有帮助。

这是一个可复制的示例,
如果您将学校改为霍格沃斯,则会显示该错误。

我的数据:

mydata <- structure(list(year = c("2001", "2002", "2001", "2002", "2001","2002", "2001", "2002", "2001", "2002", "2001", "2002", "2001", "2002", "2001", "2002", "2001", "2002", "2001", "2001", "2002"), school = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Beauxbatons", "Hogwarths"), class = "factor"), grade = c(67, 69, 72, 90, 75, 85, 13, 45, 12, 90, 75, 85, 13, 45, 12, 67, 69, 72, 67, 69, 72), magic = structure(c(1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("black", "white"), class = "factor")), row.names = c(NA, -21L), class = c("tbl_df", "tbl", "data.frame"))

我的闪亮应用程序:

library(shiny)
library(tidyverse)

ui <- fluidPage(

    selectInput("school",
            label = h3("Choose a school"),
            choices = levels(mydata$school)
    ),
    ### Choose type of magic
    selectInput("magic",
                label = "Choose magic type",
                choices = levels(mydata$magic)),


    plotlyOutput("plot_school")

)

server <- function(input, output) {

    output$plot_school <- renderPlotly({

            mydata %>%
                    filter(school == input$school, magic == input$magic) %>% 
                    group_by(year) %>% 
                    summarise(m = mean(grade), n=n()) %>%
                    filter(n > 5) %>% 
                    plot_ly(type = "scatter") %>%
                    add_trace(
                            x = ~ year,
                            y = ~ m,
                            text = ~paste('number: ', n),
                            type = 'bar'
                    )
    }) 
}
# Run the application 
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

您可以使用validate进行此操作。它使用need检查条件,如果满足条件则继续,否则为用户显示自定义消息。

您可以首先基于(n > 5)过滤数据。然后检查此数据是否有任何行。如果是,则将其绘制出来,否则,请发送一条消息。

output$plot_school <- renderPlotly({

    filtered_data <- mydata %>%
        filter(school == input$school, magic == input$magic) %>% 
        group_by(year) %>% 
        summarise(m = mean(grade), n=n()) %>%
        filter(n > 5)

    # Add validate - checks if number of rows in filtered_data is > 0
    # If not, displays "Data insufficient for plot"
    validate(
      need( nrow(filtered_data) > 0, "Data insufficient for plot")
    )

    # Create plot
    filtered_data %>%
      plot_ly(type = "scatter") %>%
      add_trace(
        x = ~ year,
        y = ~ m,
        text = ~paste('number: ', n),
        type = 'bar'
      )
  })

了解有关验证here的更多信息。