Search code examples
rlatexxtable

Boldify the contents of bottom row in xtable


How can I bold the contents of the last row of xtable?. The bottom row contains sums and I would like it boldified.

I use the following:

<<eval=TRUE,echo=FALSE,results='asis',warning=FALSE,message=FALSE,error=FALSE>>=

test.xt <- xtable(test, label="table", caption='test')
align(test.xt) <- "|l|l|r|r|r|r|r|r|"
print(test.xt, tabular.environment='tabularx', include.rownames = FALSE,  width="\\textwidth", floating=FALSE)
@

Solution

  • Here's a working example (in Rmarkdown, but should be easily adaptable.

    ---
    title: "Untitled"
    output: pdf_document
    header-includes:
      - \usepackage{tabularx}
      - \usepackage{array}
    ---
    
    ```{r, eval=TRUE,echo=FALSE,results='asis',warning=FALSE,message=FALSE,error=FALSE}
    library(xtable)
    test <- rbind(mtcars[1:10, 1:5], 
                  colSums(mtcars[1:10, 1:5]))
    rownames(test)[11] <- "Sum"
    
    test[11, ] <- paste0("BOLD", test[11, ])
    
    bold.somerows <- 
            function(x) gsub('BOLD(.*)',paste('\\\\textbf{\\1','}'),x)
    
    
    test.xt <- xtable(test, label="table", caption='test')
    align(test.xt) <- "|l|l|l|r|r|r|"
    print(test.xt, tabular.environment='tabularx', include.rownames = FALSE,  width="\\textwidth", floating=FALSE, sanitize.text.function = bold.somerows)
    ```
    

    And if you can manage without borders for now, you can use pixiedust (table borders in LaTeX documents are the next thing on the to do list for pixiedust and should be done in a few weeks).

    ```{r}
    library(pixiedust)
    test <- rbind(mtcars[1:10, 1:5], 
                  colSums(mtcars[1:10, 1:5]))
    rownames(test)[11] <- "Sum"
    
    dust(test, keep_rownames = TRUE) %>%
      sprinkle(rows = 11, bold = TRUE) %>%
      sprinkle_print_method("latex")
    ```