I am trying to create a Shiny app to display data that is collected real time. For this I am using invalidateLater(5000, session)
to periodically update the data in R.
Here is the outline of my server.R
file:
library(shiny)
library(magrittr)
# Function to get new observations
get_new_data <- function(){
data <- rnorm(5) %>% rbind %>% data.frame
return(data)
}
# Initialize my_data
my_data <- get_new_data()
# Function to update my_data
update_data <- function(){
my_data <- rbind(get_new_data(), my_data)
}
shinyServer(function(input, output, session){
# Plot the 30 most recent values
output$first_column <- renderPlot({
invalidateLater(5000, session)
update_data()
plot(X1 ~ 1, data=my_data[1:30,], ylim=c(-3, 3), las=1)
})
})
The problem I am having is that I want to show the N most recent values but can't figure out how to keep the old values. So instead of plotting the most recent 30 values I get a plot of 1 value.
Does anyone know the correct way to setup a Shiny app to update with new data while keeping the old?
This works for me:
library(shiny)
library(magrittr)
ui <- shinyServer(fluidPage(
plotOutput("first_column")
))
server <- shinyServer(function(input, output, session){
# Function to get new observations
get_new_data <- function(){
data <- rnorm(5) %>% rbind %>% data.frame
return(data)
}
# Initialize my_data
my_data <<- get_new_data()
# Function to update my_data
update_data <- function(){
my_data <<- rbind(get_new_data(), my_data)
}
# Plot the 30 most recent values
output$first_column <- renderPlot({
print("Render")
invalidateLater(1000, session)
update_data()
print(my_data)
plot(X1 ~ 1, data=my_data[1:30,], ylim=c(-3, 3), las=1, type="l")
})
})
shinyApp(ui=ui,server=server)
The problem was just that my_data was updated in the wrong scope. Just remember to not keep on rbinding forever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With