Rahul R Kulkarni
Rahul R Kulkarni

Reputation: 167

How to rbind new rows to a data table at certain time intervals in Shiny dashboard?

I am creating a shiny app with 2 outputs datatableoutput and plotoutput.I have 2 variables st and et in a data frame which will be initialized to a value, i need to add new rows to the existing data frame which has the following logic
1. New st value is previous value of et.
2. New et value is previous value of st - 1000.
3. New value ofst and et should be added as new row in my dataframe after every 5 seconds.
Based on newly added rows the line graph should get updated.

Below are my ui.r and server.r codes,currently i am able to create new values of st and et according to the logic but failed to add new rows and plot the graph

Ui.r

 library(shiny)

shinyUI(fluidPage(

 titlePanel("Incremental Plots"),

 sidebarLayout(
   sidebarPanel(),

   mainPanel(
      tableOutput('var')
    )
  )
))

Server.r

library(shiny)
start_time <- 100000
end_time <- start_time - 1000
shinyServer(function(input,output,session){
   omega <- reactive({
    invalidateLater(1000, session)

   #dataf <<- data.frame(st = c(start_time),et = c(end_time))
   return(dataf)
   })

  # update non reactive value
   observe({
    omega()
    start_time <<- end_time
    end_time <<- start_time - 1000
    dataf <<- data.frame(st = start_time,et = end_time)


  })

  output$var <- renderTable(omega())
})

Upvotes: 3

Views: 684

Answers (1)

Florian
Florian

Reputation: 25395

You could use a combination of reactiveVal and observe for that. Note that you can call the value of a reactiveVal named x with x(), and you can set its value to y by doing x(y). A working example is given below, hope this helps!


enter image description here


library(shiny)

ui<- shinyUI(fluidPage(

  titlePanel("Incremental Plots"),      
  sidebarLayout(
    sidebarPanel(),        
    mainPanel(
      tableOutput('var')
    )
  )
))

start_time <- 100000
end_time = start_time - 1000

server<- function(input,output,session){

  # Initialize
  reval_omega <- reactiveVal(data.frame(st = c(start_time),et = c(end_time)))
  reval_start <- reactiveVal(start_time)
  reval_end <- reactiveVal(end_time)

  # update our reactiveVal 
  observe({
    invalidateLater(1000, session) # every second
    isolate({
      reval_start(reval_end()) # set start time to current end time
      reval_end(reval_start() - 1000) # set end time to start - 1000
      omega_new <- data.frame(st = reval_start(),et = reval_end()) # create a new row for the dataframe
      reval_omega(rbind(reval_omega(),omega_new)) # rbind the reval_omega() and the new row, and store result in reval_omega()
    })
  })
  output$var <- renderTable(reval_omega())
}

shinyApp(ui,server)

Upvotes: 3

Related Questions