【问题标题】:Pass data from one reactive part to other in shiny以闪亮的方式将数据从一个反应部分传递到另一个
【发布时间】:2015-08-04 09:12:40
【问题描述】:

在下面闪亮的应用程序中,我想使用来自reactive 的数据框dt 称为数据,在renderPlot 中。

我通过ggplot(dt, aes(x, y)) + geom_point()ggplot(data(), aes(x, y)) + geom_point() 尝试了不同的方法

我只是不知道如何将数据帧从一个反应部分传输到另一个。

编辑
我想我通过使用找到了解决方案:ggplot(data()$dt, aes(x,y) + ... 但现在问题似乎出在dplyr 包中的filter 中。

有什么建议吗?

服务器:

# server

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

df <- data.frame(x = rnorm(100), y = rnorm(100)) %>%
  mutate(id = ntile(x, 4))

shinyServer(function(input, output) {


  data <- reactive({

    dt <- dt %>%
      filter(id == input$id)

  })

  output$plot <- renderPlot({

    ggplot(dt, aes(x,y) +
      geom_point()

  })


})

用户界面:

## ui

library(shiny)
library(ggplot2)

shinyUI(fluidPage(

  sidebarPanel(width = 2,

               selectInput("id", 
                           "Select ID:",
                           c(1:4))

               ),
  mainPanel(width = 10,

            plotOutput("plot")

            )

))

【问题讨论】:

    标签: r shiny dplyr


    【解决方案1】:

    您的代码中有一些错误(您提供的代码甚至无法运行),但最重要的是您必须了解反应式的工作原理。我建议再次阅读闪亮的教程,尤其是关于反应变量的部分。渲染绘图时,您希望使用 data 的值,而不是 dt 的值。

    其他错误:

    • 您定义了一个数据框df,但在后续代码中您使用的是不存在的变量dt
    • ggplot 调用没有右括号

    这是您的代码的工作版本:

    df <- data.frame(x = rnorm(100), y = rnorm(100)) %>%
      mutate(id = ntile(x, 4))
    
    runApp(shinyApp(
      ui = fluidPage(
        sidebarPanel(width = 2,
    
                     selectInput("id", 
                                 "Select ID:",
                                 c(1:4))
    
        ),
        mainPanel(width = 10,
    
                  plotOutput("plot")
    
        )
      ),
      server = function(input, output, session) {
    
        data <- reactive({
    
          df <- df %>%
            filter(id == input$id)
          df
        })
    
        output$plot <- renderPlot({
    
          ggplot(data(), aes(x,y)) +
                   geom_point()
    
        })
    
      }
    ))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2015-09-28
      • 2019-07-05
      • 2020-02-22
      • 2018-10-09
      • 2021-07-19
      • 1970-01-01
      相关资源
      最近更新 更多