【问题标题】:Access data created from reactive function to define reactiveValues in Shiny访问从反应函数创建的数据以在 Shiny 中定义反应值
【发布时间】:2015-07-21 12:05:19
【问题描述】:

我正在探索使用闪亮的交互式 ggplot2 的可能性。受this 的启发,我创建了一个闪亮的应用程序,它可以从数据集中排除点,并绘制被排除点具有不同颜色的数据。

app.R

library(shiny)
library(ggplot2)
server<-function(input, output) {
  data <- reactive({
    set.seed(10)
    df=data.frame(x=rnorm(100),y=rnorm(100))
    df
  })

  vals<-reactiveValues(keeprows=rep(TRUE, 100))

  output$plot1 <- renderPlot({
    df=data()
    keep=df[vals$keeprows, ,drop=FALSE]
    exclude=df[!vals$keeprows, ,drop=FALSE]
    plot=ggplot(data=keep,aes(x,y))+geom_point()+theme_bw()+
      geom_point(data=exclude,fill=NA,col="black",alpha=0.75,shape=21)
    plot
  })

  observeEvent(input$plot1_click,{
    df=data()
    res <- nearPoints(df, input$plot1_click, allRows = TRUE,threshold=5)
    vals$keeprows <- xor(vals$keeprows, res$selected_)

  })

}

ui <- fluidPage(

  titlePanel("Reactive test"),


  mainPanel(
    plotOutput("plot1",click="plot1_click")
  )
)

shinyApp(ui = ui, server = server)

这很好用,但现在我希望能够定义 vals:

vals<-reactiveValues(keeprows=rep(TRUE,nrow(CustomDataInput))

在我的示例中,我尝试从 data() 中创建的数据中访问行数:

vals<-reactiveValues(keeprows=rep(TRUE,nrow(data()))

这给了我一个错误,因为我试图在非反应性环境中访问反应性变量。有没有办法访问在反应函数中创建的数据来定义反应值?

感谢您的宝贵时间!

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    这个错误几乎解决了问题。正确的做法如下。

    library(shiny)
    library(ggplot2)
    server<-function(input, output) {
    
      vals <- reactiveValues()
      data <- reactive({
        set.seed(10)
        df=data.frame(x=rnorm(100),y=rnorm(100))
        vals$keeprows = rep(TRUE,nrow(df))
        df
      })
    
      #vals<-reactiveValues(keeprows=rep(TRUE,100))
      output$plot1 <- renderPlot({
        df=data()
        keep=df[vals$keeprows, ,drop=FALSE]
        exclude=df[!vals$keeprows, ,drop=FALSE]
        plot=ggplot(data=keep,aes(x,y))+geom_point()+theme_bw()+
          geom_point(data=exclude,fill=NA,col="black",alpha=0.75,shape=21)
        plot
      })
    
      observeEvent(input$plot1_click,{
        df=data()
        res <- nearPoints(df, input$plot1_click, allRows = TRUE,threshold=5)
        vals$keeprows <- xor(vals$keeprows, res$selected_)
    
      })
    
    }
    
    ui <- fluidPage(
    
      titlePanel("Reactive test"),
    
    
      mainPanel(
        plotOutput("plot1",click="plot1_click")
    
      )
    )
    
    shinyApp(ui = ui, server = server)
    

    事先声明vals 变量并在reactive() 函数中使用该变量将变量发送到vals,如上所示。你应该没事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2021-05-17
      • 2021-11-19
      • 1970-01-01
      • 2017-02-03
      • 2019-12-17
      相关资源
      最近更新 更多