I am trying (as a simple example) to make a Shiny app that graphs a single point whose coordinates update periodically using reactiveTimer()
. Here is what I have:
library(shiny)
library(ggplot2)
server <- shinyServer(function(input, output, session) {
autoInvalidate <- reactiveTimer(4000, session)
output$myplot <- renderPlot({
autoInvalidate()
coords_curr <- as.data.frame(t((runif(2))))
ggplot(coords_curr, aes(V1,V2)) +
geom_point() +
xlim(0,1) + ylim(0,1)
})
})
ui <- shinyUI(fluidPage(
mainPanel(plotOutput("myplot"))
))
shinyApp(ui, server)
Is there a way to have this iteration's coordinates depend on the coordinates from the previous iteration? So, for instance, I would like to have something like:
coords_curr <- coords_prev + as.data.frame(t((runif(2, min=0, max=0.25))))
where coords_prev
are the previous iteration's coords_curr
. Is there a way to save information from the previous iteration?
Thank you!
One way of doing it is by using global assignment operator <<-
.
rm(list = ls())
library(shiny)
library(ggplot2)
server <- shinyServer(function(input, output, session) {
autoInvalidate <- reactiveTimer(500, session)
# Initiate the values
coords_prev <<- 0
output$myplot <- renderPlot({
autoInvalidate()
coords_curr <- coords_prev + as.data.frame(t((runif(2, min=0, max=0.25))))
# Add previous value to it
coords_prev <<- coords_curr
ggplot(coords_curr, aes(V1,V2))+ geom_point() + xlim(0,1) + ylim(0,1)
})
})
ui <- fluidPage(mainPanel(plotOutput("myplot")))
shinyApp(ui, server)
You can use reactiveValues
:
library(shiny)
library(ggplot2)
server <- shinyServer(function(input, output, session) {
autoInvalidate <- reactiveTimer(500, session)
myReactives <- reactiveValues(myCords = c(0,0))
output$myplot <- renderPlot({
autoInvalidate()
coords_curr <- isolate({
myReactives$myCords + as.data.frame(t((runif(2, min=0, max=0.25))))
})
# Add previous value to it
myReactives$myCords <- coords_curr
ggplot(coords_curr, aes(V1,V2))+ geom_point() + xlim(0,1) + ylim(0,1)
})
})
ui <- fluidPage(mainPanel(plotOutput("myplot")))
shinyApp(ui, server)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.