R – shiny R renderTable right alignment

rshiny

I have a shiny R application in which I'm using "renderTable" function to render the table that is dynamically created.
The table may have 3 character columns and 4 numeric columns in one case and has 2 character columns and 2 numeric columns in another case.
The renderTable code from ui.R is :

     output$table1 <- renderTable({
                d1<-data()
             print(format(d1, big.mark=",", scientific=FALSE,justify="right", nsmall=0))

     })

This is working for all format options specified except for justify. All numeric columns are left justified in the output.

Can anyone shed some light on why?

Best Answer

You could wrap your tableOutput with an uiOutput (a.k.a. htmlOutput) in order to change the align parameter whenever the data changes. Here is an Example.

library(shiny)

server <- function(input, output, session) {
  output$table_wrapped = renderUI({
    # this table can be reactive since it is inside a render function
    reactiveTable = data.frame(
      name=sapply(1:input$nrows, function(x) paste(
        rep(letters[x], x), 
        collapse=''))
    )
    for( i in 1:input$ncols )
      reactiveTable[letters[i]] = seq(100, 100*input$nrows, by = 100)

    # calculate alignment vector (something like "lrrrrr")
    align = paste(rep('l', ncol(reactiveTable)))
    numeric_columns = which(as.logical(lapply(reactiveTable, is.numeric)))
    align[numeric_columns] = "r"
    align = paste(align, collapse ="")

    # create tableoutput. Since this is inside a render Function, 
    # the alignment changes with the inputs
    output$table <- renderTable({reactiveTable}, align = align)

    # return the tableOutput
    tableOutput('table')
  })
}

ui <- fluidPage(
  inputPanel(
    sliderInput("ncols", "Number of numeric columns", 4, 10, 4),
    sliderInput("nrows", "Number of rows", 4, 10, 4)
  ),
  uiOutput('table_wrapped')
)

runApp(list(ui=ui, server=server))

enter image description here

Related Topic