Search code examples
rreactable

R reactable format multiple columns as percentage


I'd like format several columns in my dataframe as percentage with reactable package. I know how can I do it if I specify all of them row by row, but I'd like to achieve same output only if I specify starting column number, in this case from 2nd column.

reactable(
  data.frame(
    id = seq(1, 10, 1),
    sh = seq(.1, 1, .1),
    ar = seq(.1, 1, .1),
    br = seq(.1, 1, .1)
  ), 
  columns = list(
    sh = colDef(format = colFormat(percent = TRUE, digits = 1)),
    ar = colDef(format = colFormat(percent = TRUE, digits = 1)),
    br = colDef(format = colFormat(percent = TRUE, digits = 1))
    )
  )

Solution

  • One option would be to use e.g. lapply to create a named list of colDefs:

    library(reactable)
    
    dat <- data.frame(
      id = seq(1, 10, 1),
      sh = seq(.1, 1, .1),
      ar = seq(.1, 1, .1),
      br = seq(.1, 1, .1)
    )
    
    cols <- names(dat)[-1]
    col_defs <- lapply(
      cols,
      \(x) colDef(format = colFormat(percent = TRUE, digits = 1))
    )
    names(col_defs) <- cols
    
    reactable(
      dat,
      columns = col_defs
    )
    

    enter image description here