How do I make a Shiny app read continuously from a file?

余生长醉 提交于 2021-02-08 09:37:04

问题


I am writing a relatively simple Shiny app which basically needs to read a file, perform some calculations to create a new variable and output the mean value of the latest 5 points of this variable. A very simplified version of the app:

require(shiny)

x1 <- 42
df.data <- read.csv("data.csv")
df.data$y2 <- df.data$y1/x1

ui <- fluidPage(
      h5(textOutput("calc1"))
)

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

    output$calc1 <- renderText({
                    az <- nrow(df.data)
                    aa <- az - 5
                    y5m <- mean(df.data$y2[aa:az], na.rm=TRUE)
                    })
}

shinyApp(ui=ui, server=server)

The file is updated every minute by an external program. The part I am struggling with is how to keep the app reading the file (every 2 minutes for example) and keeping the mean of the last 5 minutes updated.

I have read about reactivity but I can't seem to make it work when it is about reading a file. I am new to Shiny so maybe I am missing some fundamental concept. Any suggestions, please?

reactiveFileReader is the function I have been trying to use, but can't make it work. What am I missing?

server <- function(input, output, session) {
          df.data <- reactiveFileReader(1000, NULL, "data.csv", header=F)
          output$calc1 <- renderText({ ... })
}

回答1:


By using invalidateLater() function we can do this.

require(shiny)
ui <- fluidPage(
  h5(textOutput("calc1"))
)

server <- function(input, output, session) {
  df <- reactive({
    invalidateLater(120000, session) # equivalent milliseconds for 2 minutes
    x1 <- 42
    df.data <- read.csv("data.csv")
    df.data$y2 <- df.data$y1/x1
    return(df.data)
    })
  output$calc1 <- renderText({
    az <- nrow(df())
    aa <- az - 5
    y5m <- mean(df()$y2[aa:az], na.rm = TRUE)
  })
}

shinyApp(ui=ui, server=server)


来源:https://stackoverflow.com/questions/53455448/how-do-i-make-a-shiny-app-read-continuously-from-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!