how do you change colors of certain cells in xtable markdown?

前端 未结 1 1151
挽巷
挽巷 2021-01-05 13:31

I have a data frame called j:

dput(j)

structure(list(Trans = c(89.8, 3337, NA, 97.55, NA, 3558.7, NA, 
4290.6, NA, 65.95, 94.55, 3495.9), `%CPU` = c(6.93         


        
相关标签:
1条回答
  • 2021-01-05 14:01

    Be careful with the % signs in the column names. You'll need to specify sanitizing functions for text, to deal with the LaTeX commands, and for column names to handle the percent signs.

    Use the \cellcolor command to color a cell in LaTeX table.

    Here is an example .Rmd file

    ---
    title: "Colors of xtable cells"
    header-includes:
       - \usepackage{longtable}
       - \usepackage[table]{xcolor}
       - \usepackage{colortbl}
    output:
        pdf_document
    ---
    
    Build the example data set
    
    ```{r, include = FALSE}
    library(xtable)
    j <-
      structure(list(Trans = c(89.8, 3337, NA, 97.55, NA, 3558.7, NA, 
      4290.6, NA, 65.95, 94.55, 3495.9), `%CPU` = c(6.938, 79.853, 
      1.875, 4.87, 1.46, 37.885, 1.63, 64.576, 1.165, 3.425, 5.67, 
      33.856), `%Heap Used` = c(9.9, 76.95, 3.77, 9.8, 6.73, 59.23, 
      3.94, 67.38, 3.73, 9.13, 9.57, 62.11), `Heap Usage/MB` = c(263.884, 
      1942.246, 99.104, 257.717, 178.951, 1657.447, 99.933, 2137.134, 
      96.687, 242.024, 256.302, 1646.117)), .Names = c("Trans", "%CPU", 
      "%Heap Used", "Heap Usage/MB"), class = "data.frame", row.names = c(NA, 
      -12L))
    ```
    
    Create a version of the `data.frame` with red cells for \%CPU greater than 70.
    Set the color and round to two digits.
    
    ```{r, include = FALSE}
    j[, 2] <- ifelse(j[, 2] > 70, paste("\\cellcolor{red}{", round(j[, 2], 2), "}"), round(j[, 2], 2))
    ```
    
    The resulting table is:
    
    ```{r results = "asis"}
    print(xtable(j,
                 digits = 2,
                 row.names = FALSE,
                 caption = "JVM Usage"),
          sanitize.text.function = identity,
          sanitize.colnames.function = NULL,
          caption.placement   = "top",
          tabular.environment = "longtable",
          comment = FALSE,
          floating=FALSE) 
    ```
    

    Which produces the following output:

    0 讨论(0)
提交回复
热议问题