Brilliant R renderTable Right Alignment

I have a brilliant R application in which I use the renderTable function to render a dynamically created table. A table can contain 3 character columns and 4 numeric columns in one case and has 2 character columns and 2 numeric columns in another case. RenderTable code from ui.R:

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

     })

This works for all of the specified format options, except as an excuse. All numeric columns are aligned in the output.

Can someone shed some light on why?

+3
source share
3 answers

If the number of columns is always the same, you can use the argument alignfor renderTable, for example:

library(shiny)

server <- function(input, output, session) {
    output$tab <- renderTable({
        data.frame(a=seq(100, 1000, by=100), b=sapply(1:10, function(x) paste(rep(letters[x], x), collapse='')))
    }, align='rrr')

}

ui <- fluidPage(
    tableOutput('tab')
)

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

Note that you also specified alignment for line names.

+2
source

tableOutput uiOutput (a.k.a. htmlOutput), align , . .

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

+2

if the number of columns changes, but the desired alignment is the same, you can use align = 'r'

0
source

Source: https://habr.com/ru/post/1691899/


All Articles