【问题标题】:ERROR:`data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class reactiveExpr/reactive错误:`data` 必须是一个数据框,或其他可通过`fortify()` 强制的对象,而不是具有类 reactiveExpr/reactive 的 S3 对象
【发布时间】:2020-07-24 03:36:53
【问题描述】:

我正在尝试构建一个 Corona 仪表板。如果有人从下拉列表中选择州,则将在图表中显示地区案例。例如。如果有人选择古吉拉特邦,它会在条形图中显示地区案例。有人将其更改为马哈拉施特拉邦,它应该随着马哈拉施特拉邦的地区而更新。 但我得到 “ERROR:data must be a data frame, or other object coercible by fortify(), not an S3 object with class reactiveExpr/reactive”错误。

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

ui <- fluidPage(

    # Application title
    titlePanel("Corona Data"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            selectInput(inputId = "state", 
                        label = "Select the State",
                        choices = unique(data$`Detected State`))
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("stateplot")
        )
    )
)


data <- read_excel("Live Data Worldometer.xlsx", sheet = "IndiaData")
data <- data[,c(-2,-1)]

server <- function(session, input, output) {

    d1 <- reactive({data %>% group_by(`Detected State`) %>% count(`Detected District`) %>% filter(`Detected State` == input$state)
        })

    output$stateplot <- renderPlot({
        ggplot(d1, aes(d1$`Detected District`, d1$n))+geom_bar(stat = "identity")
    })

}

# Run the application 
shinyApp(ui = ui, server = server)

This is the output I am getting

【问题讨论】:

    标签: r shiny shinydashboard


    【解决方案1】:

    d1 不是数据框,而是需要评估的表达式(reactive 不返回数据框)。在ggplot2中使用前需要激活反应元素

    server <- function(session, input, output) {
    
        d1 <- reactive({
            data %>% group_by(`Detected State`) %>% 
                     count(`Detected District`) %>%
                     filter(`Detected State` == input$state)
            })
    
        output$stateplot <- renderPlot({
            ggplot(d1(), aes(x = `Detected District`, y = n)) +
                 geom_bar(stat = "identity")
        })
    
    }
    

    【讨论】:

    • 感谢您的回复。我尝试按照您的建议更正代码。但出现以下错误。 .getReactiveEnvironment()$currentContext() 中的错误:如果没有活动的反应上下文,则不允许操作。 (你试图做一些只能在反应式表达式或观察者内部完成的事情。)
    • 对不起,我没有看到你已经添加了一个名为data的对象:它同时在你的reactive中输入和输出。您可以使用编辑后的解决方案再试一次吗? (重命名的对象)
    • 您需要调用 d1() inside renderPlot(在反应式上下文中)。
    • 哇。向你致敬。太感谢了。它工作得很好。再次感谢,非常感谢。
    • 不错!感谢@shosaco 的调试。你能接受这个答案,因为它适合你吗? (如果需要,请参阅here 获取指南)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2021-07-01
    相关资源
    最近更新 更多