Search code examples
rdplyrshinyreactiveshiny-reactivity

Shiny : impossible to do a mutate on a reactive data source (reactiveFileReader / reactivePoll)


I'm trying to build a shiny application that gets live data from a .csv file named "test.csv". Here is a example of the data :

name   age  timestamp
Paul    23  1654095025
Michael 23  1674095025
Jane    54  1654895025
Jack    31  1954095025
Luis    23  1954095025
Anna    85  1954095025

On this csv file, I would like to do some dplyr operations, like a mutate on a timestamp to convert it to datetime. To retrieve live data, I use the shiny reactiveFileReader function. Here is the code :

library(shiny)
library(shinydashboard)
library(dplyr)

ui <- fluidPage(
        mainPanel(
           tableOutput("data")
        )
    )

server <- function(input, output) {

    fileData <- reactiveFileReader(10, NULL, 'test.csv', read.csv2)
    
    output$data <- renderTable({
      fileData() %>%
        mutate(timestamp2 = as_datetime(timestamp))
    })
}

shinyApp(ui = ui, server = server)

The problem is that the mutate is not taken into account and I can't do the operation on the timestamp field, here is a copy of the table displayed in the shiny app (result of the code above) :

name    age timestamp   timestamp2
Paul    23  1654095025  1654095025.00
Michael 23  1674095025  1674095025.00
Jane    54  1654895025  1654895025.00
Jack    31  1954095025  1954095025.00
Luis    23  1954095025  1954095025.00
Anna    85  1954095025  1954095025.00

Do you know how to solve this problem? Despite my research, I have not found anyone with a similar problem.

Note: this is actually a simplified example. I'm trying to do this in a more complex shiny application with a live connection to a mongoDB database. For that, I use reactivePoll() instead of reactiveFileReader(), but the problem is the same!

Thank you


Solution

  • library(shiny)
    library(dplyr)
    
    f <- tempfile(fileext = ".csv")
    
    writeLines(text =
    'name   age  timestamp
    Paul    23  1654095025
    Michael 23  1674095025
    Jane    54  1654895025
    Jack    31  1954095025
    Luis    23  1954095025
    Anna    85  1954095025
    ', con = f)
    
    ui <- fluidPage(
      mainPanel(
        tableOutput("data")
      )
    )
    
    server <- function(input, output, session) {
      
      fileData <- reactivePoll(1000, session,
        checkFunc = function() {
          info <- file.info(f)
          return(paste(f, info$mtime, info$size))
        }, 
        valueFunc = function() {
          read.table(f, header = TRUE)
        })
      
      output$data <- renderTable({
        fileData() %>%
          mutate(timestamp2 = as.character(lubridate::as_datetime(timestamp)))
      })
    }
    
    shinyApp(ui = ui, server = server)