首页 > 解决方案 > R:将信息从反应函数传递到渲染图

问题描述

全部。我对闪亮和 R 很陌生,但我正在努力学习如何通过它。

我可以利用您的帮助学习如何将反应函数中的信息传递到 renderPlot。我已经成功地使用我的反应函数来构建一个数据框,但是当我尝试使用 ggplot 在 renderPlot 中绘制它时,数据不可用。

在 renderPlot 中,我收到“对象“产品”不存在”的错误。有什么想法吗?

server <- function(input, output) 
{
reactive_data <- reactive({

                finalData <- data.frame(ITEM_DESC=as.character(), revenue=double(), product=character())

                for (p in input$product_selection){

                    tempData <- orderData %>%
                        filter(grepl(p, ITM_DESC)) %>%
                        select(ITM_DESC, revenue) %>%
                        group_by(ITM_DESC) %>%
                        summarize(rev=sum(revenue))

                    tempData <- tempData %>% mutate(product = p)

                    if (dim(finalData)[1] == 0) {
                        finalData <- tempData
                    }
                    else{
                        finalData <- bind_rows(finalData, tempData)
                    }
                }

            })

# Render Plot
output$shinyOrders <- renderPlot(
                        ggplot(reactive_data()) +
                        geom_col(aes_string(x="product", y="rev")) +
                        theme_bw(18) +
                        theme(axis.text.x = element_text(angle = 90, hjust = 1))
                        )
}

# ---- Run App ----

shinyApp(ui, server)

标签: rshiny

解决方案


for循环不返回任何内容。观察:

(for (i in 1:3) i <- i+1)
# NULL
i
# [1] 4

我认为这使您的解决方案(未经测试):

server <- function(input, output) {
  reactive_data <- reactive({

    finalData <- data.frame(ITEM_DESC=as.character(), revenue=double(), product=character())

    for (p in input$product_selection){

      tempData <- orderData %>%
        filter(grepl(p, ITM_DESC)) %>%
        select(ITM_DESC, revenue) %>%
        group_by(ITM_DESC) %>%
        summarize(rev=sum(revenue))

      tempData <- tempData %>% mutate(product = p)

      if (dim(finalData)[1] == 0) {
        finalData <- tempData
      }
      else{
        finalData <- bind_rows(finalData, tempData)
      }
    }

    return(finalData) # <--------- you need this

  })

  # Render Plot
  output$shinyOrders <- renderPlot(
    ggplot(reactive_data()) +
      geom_col(aes_string(x="product", y="rev")) +
      theme_bw(18) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1))
  )
}

# ---- Run App ----

shinyApp(ui, server)

推荐阅读