in RStudio shiny, wishing to customize a table

前端 未结 2 706
不思量自难忘°
不思量自难忘° 2021-01-03 07:19

In an RStudio shiny application with a table produced by renderTable(), I\'d like to add a leading column of radio-buttons (reactive, of course) and change the

2条回答
  •  青春惊慌失措
    2021-01-03 08:00

    Pursuing @MadScone 's excellent advice, I came up with the following code, which is the definitive solution to
    Some additional features that make it work for me are: * the radio buttons are in column 1 (not row 1) * they belong to the same radio group * the table header row is properly formatted * the row selected by radio button receives special formatting, without needing jQuery.

    values = reactiveValues(PopRow=1)   ### To receive and hold the selected row number.
    
    f.objects_table_for_OneCT = function(){
        f.changeSelectedRow()        #### See definition below.
        df = createObjectsTable()    #### Any data frame goes here; code not provided here.
        selectedRow = values$PopRow
        header_html <- function(table_cell) paste0('', table_cell, '')
        cell_html <- function(table_cell) paste0('', table_cell, '')
        radio_html <- function(radio_name, radio_value, is_checked, radio_text) {
          paste0('', radio_text)
        }    
        row_html <- function(table_row_num) {
          table_row = df[table_row_num, ]
          cells <- sapply(table_row, cell_html)
          cells <- c(cell_html(radio_html(
                      "whichRow", table_row_num, table_row_num == selectedRow, "")),
                   cells)
          collapse_cells <- paste0(cells, collapse='')
          selectedRowStyle = "style='color:red; font-weight:bold'"
          collapse_cells <- paste0('', collapse_cells, '')
          collapse_cells 
        }
        df_rows <- sapply(1:nrow(df), row_html) 
        df_header_row <- header_html(c("CHOICE", names(df)))
        collapse_cells <- paste0(c(df_header_row, df_rows), collapse='')    
        full_table <- paste0('', 
                             collapse_cells, '
    ') return(full_table) } output$objects_table_for_OneCT = renderText({f.objects_table_for_OneCT()})

    (Concerning the last line, I habitually wrap my expr arg in a function, so I can debug. So far it's worked fine.)

    The function that responds to the radio buttons is as follows:

      f.changeSelectedRow = reactive({
        if(is.null(values$PopRow)) values$PopRow = 1
        if(!is.null(input$whichRow))   ### from the radio button set.
                 if(input$whichRow != values$PopRow) values$PopRow = input$whichRow
      })
    

提交回复
热议问题