且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

R Shiny Datatable列用行拆分

更新时间:2023-12-01 12:06:46

我使用了 mtcars 数据集的一个子集来生成此输出。下面是一个自给自足的可复制示例,一个人必须使用CSS样式来实现此效果。 。


I generate a Datatable in my shiny server like:

x=renderTable(rownames = FALSE,{...}

And have a Ui like:

 tableOutput("x")

Now I want that every second column a split is marked as line. For example:

a   b | c   d | e  ...
1   2 | 2   3 | 4  ...
4   3 | 1   2 | 3  ...
3   1 | 5   5 | 5  ...

I hope someone can help me. Thanks

I've used a subset of mtcars dataset to generate this output. Below is a self-sufficient reproducible example for the same. One has to use CSS Styling to achieve this effect. Additional Information for advanced Styling is available here

library(DT)
library(shiny)
library(datasets)


ui <- fluidPage(

  dataTableOutput("table")

)

server <- function(input, output, session) {

  mtcars <- mtcars %>% select(1:8)
  row.names(mtcars) <- NULL

  output$table <- renderDataTable({

    # Initiate Empty Vector for Alternative border formating
    alt_vector <- vector(mode = "numeric")

    # Iterate over the no. of columns in the table to generate the vector
    for (i in 1:ncol(mtcars)) { 
      if(i %% 2 == 0) 
        alt_vector <- c(alt_vector,i)
    }

      df <- datatable(mtcars,rownames = FALSE, options = list(pageLength = 25)) %>%
            # First Column Border Left
            formatStyle(c(1),`border-left` = '1px solid black') %>% 
            # Rest Alternative Bordering
            formatStyle(alt_vector,`border-right` = '1px solid black')

  })

}

shinyApp(ui, server)

Attached is a snap-shot of the formatted table from the UI.