rcorty
rcorty

Reputation: 1200

in R Shiny, update an object based on user input

I would like to have a plot of my graph (g) showing in my app at all times. I would like to have a 'default' value of g hard-coded into the app, and the user can update g via the UI. I am using the {{igraph}} library and its functions, such as make_empty_graph and add_vertices.

I believe my main issue at this point is that I hard-code g, but then the reactive version of g is really g(). I'm sure this problem has been solved many times before, but I can't see an example in the Shiny demos that does it.

Here's what I have inside server():

g <- make_empty_graph(directed = TRUE) %>%
    add_vertices(nv = 1, depth = 0L, x = 0, y = 0, cur = TRUE)

g <- eventReactive(
    eventExpr = 'investigate',
    valueExpr = {
        add_children(g = g, vidx = input$vidx)
    }
)

output$the_plot <- renderPlot(
    expr = {    
       plot_graph(g())
    }
)

add_children() and plot_graph() are defined in the global namespace. I am happy to share more code (or the whole app) if that is helpful.

Based on input from SO, the working version is:

g <- reactiveVal(
    make_empty_graph(directed = TRUE) %>%
        add_vertices(nv = 1, depth = 0L, x = 0, y = 0, cur = TRUE)
)    

observeEvent(
    eventExpr = input$investigate,
    handlerExpr = g(add_children(g = g(), vidx = input$vidx)),
    ignoreInit = TRUE
)

output$the_plot <- renderPlot(plot_graph(g()))

Upvotes: 1

Views: 488

Answers (1)

Shree
Shree

Reputation: 11140

If I understand your problem correctly, here's a way using reactiveValues and observeEvent with ignoreInit = TRUE. Below app will start off with initial value 5 in output$test but will later depend on input$slider. This way you are always referencing to a reactive value in the output.

ui <- fluidPage(
  sliderInput("slider", "Slider", 1, 10, 10),
  verbatimTextOutput("test")
)

server <- function(input, output, session) {
  graph <- reactiveValues(g = 5)# initial value

  observeEvent(input$slider, {
    graph$g <- input$slider # new value
  }, ignoreInit = TRUE)

  output$test <- renderPrint({graph$g})

}

shinyApp(ui, server)

Upvotes: 1

Related Questions