31

I have a shiny application that shows a nice html table of my data, using renderDataTable. Then I wanted to make some basic statistics, subset data and calculate means and some other data.

When showing results with renderTable, I found that date column was not shown in date format. In the figure ou can see the difference. Both tables are generated from the same dataset in the same shiny web app. Can you explain what's happening?

enter image description here

And here you can see ui.R and server.R. In this script I just want to show a table and was surprised by the different output.

ui.R

library(shiny)

# Estructura de la página (paneles)
shinyUI(pageWithSidebar(
  # Título superior
  headerPanel(""),
  # Panel lateral izquierdo - selección de datos
  sidebarPanel(
    helpText("Selecciona las fechas y el tipo de datos.
             Pulsa el botón Actualizar."),    
    selectInput("torre", "Torre:",
                list("Agres" = "mariola",
                     "Alfàs del Pi" = "shelada",
                     "Altura" = "altura",                                          
                     "Vistabella del Maestrat" = "vistabella",
                     "Xàtiva" = "xativa")),       
    selectInput("tipo", "Intervalo de datos",
                list("Diezminutales" = "-datos-10m.csv",
                     "Diarios" = "-datos-diarios.csv",
                     "Mensuales" = "-datos-mensuales.csv")),
    dateInput('date1',
              label = 'Fecha inicial',
              value = Sys.Date()),
    dateInput('date2',
              label = 'Fecha final.',
              value = Sys.Date()),
    submitButton("Actualizar"),
    helpText("
             Descarga de datos tabulados en formato CSV."),
    downloadButton('downloadData','Descargar datos')    
  ),

  # Panel principal (presentación de gráficas)
  mainPanel(
    tabsetPanel(
      tabPanel("Inicio",
               h3("Consulta de datos"),
               p(HTML("Some info.")),
               tableOutput("view")
               ),
      tabPanel("Ayuda", htmlOutput("ayuda"),id="ayuda"),
      tabPanel('Tabla de datos', dataTableOutput("table1")),      
      tabPanel('Medias', tableOutput("table2"))
    )
  )
))

and server.R

library(shiny)
library(plyr)
library(lubridate)
library(scales)

options(shiny.transcode.json = FALSE)

# Funciones
shinyServer(function(input,output){

  filename=reactive({
    paste0(input$torre,input$tipo)
    })
  day1=reactive({
    as.POSIXct(input$date1)
  })
  day2=reactive({
    as.POSIXct(input$date2)    
  })

  # Ayuda
  introFile <- './ayuda.txt'
  ayuda <- readChar(introFile, file.info(introFile)$size)
  output$ayuda <- renderText({HTML(ayuda)})

  datos2=reactive({
    fn = filename()
    f = read.csv(fn,header=T, sep=",",na.strings="-99.9")
    f$date = as.Date(f$date)
    f
  })
  datos=reactive({
    d1 <- as.Date(day1())
    d2 <- as.Date(day2())
    datos2a = datos2()
    with( datos2a , datos2a[ date >= d1 & date <= d2, ] )
  })  

  #  Tabla de datos
  output$table1 = renderDataTable({
    datos()
  }, options = list(aLengthMenu = c(12, 20, 40), iDisplayLength = 12))

  output$table2 = renderTable({
    datos()
  })

  output$downloadData <- downloadHandler(
    file = c('data.csv'),
    content = function(file) {
      write.csv(datos(), file)
    }
  )

})

Thanks in advance for your help

Henrik
  • 65,555
  • 14
  • 143
  • 159
pacomet
  • 5,011
  • 12
  • 59
  • 111
  • 1
    Why do you expect t have the same output for `renderDataTable` and `renderTable`? They are completely different. Then You should be able to reproduce the same behavior with a small shiny example ( no need to have all others UI components/server functions). You have very long noisy non reproducible example. – agstudy Feb 04 '14 at 11:39
  • 1
    @agstudy I expected the same output as I thought they were just ways of showing data, didn't know I had to format data before. I assumed `renderTable` knew date was in some date format because of `f$date = as.Date(f$date)` Thanks for your answer. – pacomet Feb 04 '14 at 12:14
  • 1
    @agstudy I'll try to do my best regarding reproducible examples next time. Thanks. – pacomet Feb 04 '14 at 12:14
  • 2
    Note that renderTable does not play nice with dates. You would need to convert them to characters. See e.g., this [discussion](https://groups.google.com/forum/?fromgroups=#!searchin/shiny-discuss/xtable$20date/shiny-discuss/-yidumRGmLI/25a3F8ojJSEJ) – Vincent Feb 04 '14 at 18:39
  • Yes @Vincent that was the point. In this case I will use `renderDataTable` when playing with dates. Thanks – pacomet Feb 05 '14 at 08:34

1 Answers1

31

There is no reason to have the same output from 2 different functions.

  • rendertable uses xtable to create the html table
  • renderDataTable uses external javascript library

You can get the same date format, you should just format your date before calling renderTable. Here a short complete example.

library(shiny)
dat <- data.frame(date=seq.Date(Sys.Date(),by=1,length.out=5),
                  temp = runif(5))

ui <- fluidPage(
    fluidRow(column(4,dataTableOutput('dto')),
             column(4,tableOutput('to')))
  )

server <- function(input,output){

  output$dto <- renderDataTable({dat})
  dat$date <- format(dat$date,'%Y-%m-%d')
  output$to <- renderTable(dat)

}

runApp(list(ui=ui,server=server))
jarlh
  • 42,561
  • 8
  • 45
  • 63
agstudy
  • 119,832
  • 17
  • 199
  • 261