Home > Back-end >  Dynamic number of table container in Shiny DT in R
Dynamic number of table container in Shiny DT in R

Time:06-04

I have problem with my DT in shiny R. suppose we have the following table:

enter image description here

I got it using the code:

sketch = htmltools::withTags(
  table(
    class = 'display',
    thead(
      tr(
        th(rowspan = 2, 'Name'),
        th(colspan = 2, '2022-06-01'),
        th(colspan = 2, '2022-06-02')
      ),
      tr(
        lapply(rep(c('Length', 'Width'), 2), th)
      )
    )
  )
)
datatable(df, container = sketch, rownames = FALSE)

I would like to be able to dynamically manage the number of containers automatically. While in the element

lapply (rep (c ('Length', 'Width'), 2), th)

it's simple, by replacing 2 with the passed parameter, I can't manage the fragment completely

   tr (
     th (rowspan = 2, 'Name'),
     th (colspan = 2, '2022-06-01'),
     th (colspan = 2, '2022-06-02')
   )

to dynamically add additional elements, i.e. obtain e.g.

   tr (
     th (rowspan = 2, 'Name'),
     th (colspan = 2, '2022-06-01'),
     th (colspan = 2, '2022-06-02'),
     th (colspan = 2, '2022-06-03'),
     th (colspan = 2, '2022-06-04'),
   )

any ideas how to get this effect? Many Thanks!

CodePudding user response:

Like this, if I understand the question:

library(htmltools)

dates <- as.Date("2022-06-01")   0:3

withTags(
  tr(
    th(rowspan = 2, 'Name'),
    lapply(dates, function(d) th(colspan = 2, d))
  )
)
# <tr>
#   <th rowspan="2">Name</th>
#   <th colspan="2">2022-06-01</th>
#   <th colspan="2">2022-06-02</th>
#   <th colspan="2">2022-06-03</th>
#   <th colspan="2">2022-06-04</th>
# </tr>
  • Related