which_command
which_command

Reputation: 511

shiny: manipulating global variables to input back into shiny

I have made a shiny app the removes outlying experimental artefacts:

df=data.frame(seq(-1000,1000), rnorm(2001)) #not real data

ui <- basicPage(
  plotOutput("plot1", click = "plot_click", brush = "plot_brush"),
  verbatimTextOutput("info"),
  plotOutput("tab")
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    plot(df[,1], df[,2])
  })

  data_new<-eventReactive(input$plot_brush,{
    da=df
    rowmin <- which(da[,1] == round(as.numeric(input$plot_brush$xmin)))
    rowmax <- which(da[,1] == round(as.numeric(input$plot_brush$xmax)))
    da[rowmin:rowmax,2] = mean(da[,2])
    da=isolate(da)

    #writeToDatabase(da)
  })
  #output$zoom<-renderable({plot(data_new()[,1], data_new()[,2])})
  output$tab=renderPlot({plot(data_new()[,1], data_new()[,2])})
}

shinyApp(ui, server)

enter image description here

This works fine but it is inconvenient that I can not permanently remove the artefacts i.e. I was wondering is there any way to make the values of the non-reactive variable permanently retain the changes made rather than the original incorrect data frame being replotted each time?

I have tried using a function that corrected the faulty data-variable 'df':

change=reactive(function(d){
    rowmin <- which(d[,1] == round(as.numeric(input$plot_brush$xmin)))
    rowmax <- which(d[,1] == round(as.numeric(input$plot_brush$xmax)))
    d[rowmin:rowmax,2] = mean(d[,2])
    return(isolate(d))
  })
isolate(change(df))

but I get the following error:

Listening on http://127.0.0.1:6183
Warning: Error in change: unused argument (df)
Stack trace (innermost first):
    52: change
    51: is.data.frame
    50: write.table
    43: isolate
    42: server [/Users/Downloads/test.R#20]
     1: runApp
Error in change(df) : unused argument (df)

This was a starter test to see if I could dynamically update the variable. All of this is with the aim of being able to successively view and eliminate each of the sharp error peaks in my data shown above- rather than the code re-running on the same immutable (from shiny's perspective) variable each time??

Upvotes: 0

Views: 769

Answers (1)

HubertL
HubertL

Reputation: 19544

You probably want to use reactiveValues:

server <- function(input, output) {
  my <- reactiveValues(df=data.frame(seq(-1000,1000), rnorm(2001))) # Initialize df

  output$plot1 <- renderPlot({plot(my$df[,1], my$df[,2])})

  observeEvent(input$plot_brush,{
    rowmin <- which(my$df[,1] == round(as.numeric(input$plot_brush$xmin)))
    rowmax <- which(my$df[,1] == round(as.numeric(input$plot_brush$xmax)))
    my$df[rowmin:rowmax,2] <- mean(my$df[,2]) # Update df
  })
}

Upvotes: 1

Related Questions