title: How should I format across rows of a gt table efficiently in R?
body: <p>If I want to efficiently format rows of a gt table, is there a better method than what I have shown below. </p>
  
  <p>Some rows are character, and so need no formatting, 
  some are numbers where one decimal place is required,
  some are numbers where two decimal places is required,
  and some are percentages where two decimal places is required. Whatever is done, should ideally generalise to other possible formats.</p>
  
  <p>I create a data frame that creates the specification for formatting, but each format requires a separate command in the pipe.</p>
  
  <pre><code>library(dplyr)
  library(gt)
  
  #create small dataset
  gtcars_8 &lt;-
    gtcars %&gt;%
    dplyr::group_by(ctry_origin) %&gt;%
    dplyr::top_n(2) %&gt;%
    dplyr::ungroup() %&gt;%
    dplyr::filter(ctry_origin != "United Kingdom")
  
  #transpose data
  row_labels &lt;- colnames(gtcars_8)
  gtcars_8_t &lt;- as.data.frame(t(as.matrix(gtcars_8)))
  gtcars_8_t$row_labels &lt;- row_labels
  my_column_names &lt;- colnames(gtcars_8_t)[1:8]
  
  #format data
  format_specs &lt;- as.data.frame(row_labels[1:10])
  format_specs$type     &lt;- c("c","c","n","c","c","n","n","n","n","p")
  format_specs$decimals &lt;- c( 0 , 0 , 0 , 0 , 0 , 1 , 2 , 2 , 1 , 2 )
  format_specs
  
  #make basic gt table
  gtcars_8_t %&gt;%
    slice(1:10) %&gt;% 
    gt()
  
  #make gt table with formats hardcoded (desired output)
  gtcars_8_t %&gt;%
    slice(1:10) %&gt;% 
    gt() %&gt;% 
    cols_move_to_start("row_labels") %&gt;% 
    #format for rows where: type = n, and decimals = 1
    fmt(columns = vars(my_column_names),
        rows = which(format_specs$type  == "n" &amp; format_specs$decimals == 1 ), 
        fns = function(x) { 
          formatC(as.numeric(x), digits = 1, format = "f")
        } ) %&gt;% 
    #format for rows where: type = n, and decimals = 2
    fmt(columns = vars(my_column_names),
        rows = which(format_specs$type  == "n" &amp; format_specs$decimals == 2 ), 
        fns = function(x) { 
          formatC(as.numeric(x), digits = 2, format = "f")
        } ) %&gt;% 
    #format for rows where: type = p, and decimals = 2
    fmt(columns = vars(my_column_names),
        rows = which(format_specs$type  == "p" &amp; format_specs$decimals == 2 ), 
        fns = function(x) { 
          paste0(formatC(as.numeric(x), digits = 2, format = "f"),"%")
        } ) 
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/CvcOD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CvcOD.png" alt="result"></a></p>
  
  <p>While not quite the same, applying formatting in gt appears to be a bit trickier than one might first expect ( <a href="https://stackoverflow.com/questions/61435048/conditional-formatting-of-multiple-columns-in-gt-table">eg</a>). </p>