7

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.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))

If I want to color code a cell based on threshold in r markdown, how would I do that?

For example if %CPU>70, I need to color code that cell to be red.

I can print it in r markdown like this:

print(xtable(j_cor,digits=2,row.names=FALSE,caption="JVM Usage"),caption.placement="top", tabular.environment="longtable",comment=FALSE,floating=FALSE)

But I like to place colors in the cells based on threshold r markdown Any ideas?

I have tried something like this, but the color or the cell did not change in pdf file:

j[,2] = ifelse(j[,2] < 60, paste0("\\colorbox{red}{", j[,2], "}"), j[,2])


sessionInfo()

R version 3.2.4 (2016-03-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats4    grid      stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] ggthemes_3.4.0    flexclust_1.3-4   modeltools_0.2-21 lattice_0.20-35   tidyr_0.6.1       jsonlite_1.4      Rcpp_0.12.10      lazyeval_0.2.0   
 [9] knitr_1.16        gridExtra_2.0.0   xtable_1.8-0      data.table_1.9.6  cowplot_0.6.2     reshape2_1.4.1    corrplot_0.77     scales_0.4.1     
[17] stringr_1.0.0     chron_2.3-47      ggplot2_2.2.1     dplyr_0.5.0       purrr_0.2.2       xml2_1.0.0        plyr_1.8.4        RCurl_1.95-4.7   
[25] bitops_1.0-6      XML_3.98-1.3      httr_1.0.0        rmarkdown_1.5    

loaded via a namespace (and not attached):
 [1] tools_3.2.4      digest_0.6.12    evaluate_0.10    tibble_1.3.0     gtable_0.2.0     DBI_0.6-1        parallel_3.2.4   yaml_2.1.14     
 [9] rprojroot_1.2    R6_2.2.1         magrittr_1.5     backports_1.1.0  htmltools_0.3.5  assertthat_0.2.0 colorspace_1.3-2 labeling_0.3    
[17] stringi_1.1.5    munsell_0.4.3 

I have copied the exact text to my Rstudio and tried to run it, I am getting this error:

"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS test_color.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output test_color.pdf --template "C:\R\win-library\3.2\rmarkdown\rmd\latex\default.tex" --highlight-style tango --latex-engine xelatex --variable graphics=yes --variable "geometry:margin=1in" 
! LaTeX Error: Missing \begin{document}.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              

l.1 <

pandoc.exe: Error producing PDF from TeX source
Error: pandoc document conversion failed with error 43
In addition: Warning message:
running command '"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS test_color.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output test_color.pdf --template "C:\Documents\R\win-library\3.2\rmarkdown\rmd\latex\default.tex" --highlight-style tango --latex-engine xelatex --variable graphics=yes --variable "geometry:margin=1in"' had status 43 
user1471980
  • 10,127
  • 48
  • 136
  • 235
  • @user20650, when I include , sanitize.text.function = identity, I get this error: pandoc.exe: Error producing PDF from TeX source Error: pandoc document conversion failed with error 43 In addition: There were 20 warnings (use warnings() to see them) Execution halted – user1471980 Jun 05 '17 at 14:44
  • Did you try just running the answer at the link without changing anything - I just reran it without issue. – user20650 Jun 05 '17 at 14:57
  • yes, I get this error: output file: test.knit.md ! Package inputenc Error: Unicode char \u8: not set up for use with LaTeX. See the inputenc package documentation for explanation. Type H for immediate help. Try running pandoc with --latex-engine=xelatex. pandoc.exe: Error producing PDF from TeX source Error: pandoc document conversion failed with error 43 In addition: Warning message: – user1471980 Jun 05 '17 at 15:07
  • I cant reproduce but several tex questions on this, and maybe relevant https://stackoverflow.com/questions/32794157/package-inputenc-error-unicode-char-u8-in-rstudio – user20650 Jun 05 '17 at 15:14
  • where do you change this line: --latex-engine=xelatex – user1471980 Jun 05 '17 at 15:35
  • from the example from the [first link](https://stackoverflow.com/questions/40895829/how-can-xtable-do-cell-coloring/40897036#40897036) the `output:` is specified at the start. Just amend this with the code from [the second link](https://stackoverflow.com/questions/32794157/package-inputenc-error-unicode-char-u8-in-rstudio?answertab=votes#tab-top) – user20650 Jun 05 '17 at 15:44
  • ok, I've put there then now it is saying \begin{document} section is missing. I am using knitr and rmarkdown to generate pdf. I am confused, this is not working. when I take out "sanitize.text.function = identity", from the print(xtable) it works. – user1471980 Jun 05 '17 at 16:03
  • What code are you using to output the pdf: ? `rmarkdown::render("so_ex.Rmd")` ? – user20650 Jun 05 '17 at 16:18
  • I get this error: output file: test.knit.md ! LaTeX Error: Missing \begin{document}. See the LaTeX manual or LaTeX Companion for explanation. Type H for immediate help. ... l.1 < pandoc.exe: Error producing PDF from TeX source Error: pandoc document conversion failed with error 43 – user1471980 Jun 05 '17 at 16:27
  • Did you copy and paste the code from the other answer or did you retype the code. Some tex questions/answers suggest some end of line or extra characters (that may not be visible in your text editor) can be introduced when copy/pasting - so maybe try actually typing the commands in a new text file.. ps can you add the results of `seesionInfo()` to your question in case its relevant please. – user20650 Jun 07 '17 at 19:27
  • maybe relevant https://tex.stackexchange.com/questions/82818/latex-error-missing-begindocument , https://tex.stackexchange.com/questions/138631/latex-error-missing-begin-document , http://www.tex.ac.uk/FAQ-missbegdoc.html , https://stackoverflow.com/questions/30543113/error-missing-begindocument-in-latex – user20650 Jun 07 '17 at 19:38

1 Answers1

1

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:

enter image description here

Peter
  • 7,460
  • 2
  • 47
  • 68
  • output file: test_color.knit.md ! Package inputenc Error: Unicode char \u8: not set up for use with LaTeX. See the inputenc package documentation for explanation. Type H for immediate help. ... Try running pandoc with --latex-engine=xelatex. pandoc.exe: Error producing PDF from TeX source Error: pandoc document conversion failed with error 43 In addition: Warning message:_ – user1471980 Jun 13 '17 at 19:25
  • I have updated the post with the error, I am getting now with your exact post. – user1471980 Jun 13 '17 at 19:50
  • I get this error: ! Package inputenc Error: Unicode char \u8: not set up for use with LaTeX. See the inputenc package documentation for explanation. Type H for immediate help. Try running pandoc with --latex-engine=xelatex. pandoc.exe: Error producing PDF from TeX source Error: pandoc document conversion failed with error 43 – user1471980 Jun 20 '17 at 14:20
  • These lines at the top are causing the issue, coloring the cells. Any ideas how I could address this: - \usepackage[table]{xcolor} - \usepackage{colortbl} – user1471980 Jun 22 '17 at 17:55
  • 1
    Have you tried adding `- \usepackage[utf8]{inputenc}` to the `header-includes:` section? – Peter Jun 22 '17 at 18:04
  • I now get this error: ! Undefined control sequence. l.159 2 & 3337.00 & \cellcolor – user1471980 Jun 22 '17 at 18:49
  • Hi Peter, looks like I am making a progress. I've changed cellcolor to just color, I do see the text color changing now. Is it possible to that it is not cellcolor, something else as key word? – user1471980 Jun 22 '17 at 19:08
  • \\cellcolor does not work. Do I need a special package/library for the cellcolor to work? – user1471980 Jul 25 '17 at 18:44
  • `\usepackage[table]{xcolor}` – Peter Jul 25 '17 at 20:09
  • no luck. I still get this error: "! Undefined control sequence.l.155 1 & A & \cellcolor" – user1471980 Jul 25 '17 at 20:18
  • can you edit your question, or post a new one, to show what is in your yaml header? – Peter Jul 25 '17 at 20:21
  • can you please take a look at this. I've tried every suggestions, still getting the same error: https://stackoverflow.com/questions/45311909/how-do-you-color-the-cell-in-rmarkdown-pdf-output?noredirect=1#comment77587162_45311909 – user1471980 Jul 25 '17 at 20:28