Home > Software design >  Unused Argument Error when trying to update reactiveVal
Unused Argument Error when trying to update reactiveVal

Time:10-26

I'm trying create a plot where I'm able to zoom in on a range and the y-axis rescales. Similar to Rescaling of y axis on an interactive plot depending on zoom except that I would like it to happen on double click.

library(shiny)
library(tidyverse)

ui <- fluidPage(
  sidebarPanel(
    actionButton('getdata', 'Get Data')  
  ),
  mainPanel(
    plotOutput('plot', brush = brushOpts(id = 'brush'), dblclick = 'dclick')  
  )
)

server <- function(input, output, session) {
  
  
  dat <- eventReactive(input$getdata, {
    tibble('BusDate' = Sys.Date() - 0:10, 'Val' = rnorm(11))
  })
  
  
  dat2 <- reactive(dat())
  observeEvent(input$dclick, {
    brush <- input$brush

    maxy <- brush$xmax
    miny <- brush$xmin

    if (is.null(miny)){
      dat2(dat())
    }else{
      dat2(dat() %>% filter(BusDate > miny & BusDate < maxy))
    }
  }, ignoreInit = TRUE)

  output$plot <- renderPlot({
    ggplot(dat2(), aes(x = BusDate, y = Val))   geom_line()
  })
    
}

shinyApp(ui, server)

I keep getting an error that doesn't allow me to update dat2 within observe event.

Error in dat2: unused argument (dat() %>% filter(BusDate > miny & BusDate < maxy))

How do I update dat2 within observeEvent? I understand that its easier to update reactiveValues instead but I would like to know how it works specifically with reactiveVal

CodePudding user response:

Try this:

library(shiny)
library(tidyverse)

ui <- fluidPage(
    sidebarPanel(
        actionButton('getdata', 'Get Data')  
    ),
    mainPanel(
        plotOutput('plot', brush = brushOpts(id = 'brush'), dblclick = 'dclick')  
    )
)

server <- function(input, output, session) {
    
    
    dat <- eventReactive(input$getdata, {
        tibble('BusDate' = Sys.Date() - 0:10, 'Val' = rnorm(11))
    })
    
    
    dat2 <- reactiveVal()
    observeEvent(input$dclick, {
        brush <- input$brush
        
        maxy <- brush$xmax
        miny <- brush$xmin
        
        if (is.null(miny)){
            dat2(dat())
        }else{
            dat2(dat() %>% filter(BusDate > miny & BusDate < maxy))
        }
    }, ignoreInit = TRUE)
    
    output$plot <- renderPlot({
        df <- if(is.null(dat2())) dat() else dat2()
        ggplot(df, aes(x = BusDate, y = Val))   geom_line()
    })
    
}

shinyApp(ui, server)

You are confusing reactive with reactiveVal. You can only update the value of reactive within its definition. Update with obj(xxx) is for reactiveVal.

  • Related