• R/O
  • SSH

Commit

Tags
No Tags

Frequently used words (click to add to your profile)

javac++androidlinuxc#windowsobjective-ccocoa誰得qtpythonphprubygameguibathyscaphec計画中(planning stage)翻訳omegatframeworktwitterdomtestvb.netdirectxゲームエンジンbtronarduinopreviewer

Commit MetaInfo

Revision0c299aaca51f6009264df8f64cc071c194bbaa23 (tree)
Time2020-07-17 05:02:20
AuthorLorenzo Isella <lorenzo.isella@gmai...>
CommiterLorenzo Isella

Log Message

A simple example for conditional formatting for the color of a table with percentages. The trick is to include the formattable library but not to treat the % sign like in latex.

Change Summary

Incremental Difference

diff -r 79d119ff7cf7 -r 0c299aaca51f R-codes/test_percentage_kable.R
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/R-codes/test_percentage_kable.R Thu Jul 16 22:02:20 2020 +0200
@@ -0,0 +1,104 @@
1+
2+library(tidyverse)
3+library(kableExtra)
4+library(formattable)
5+
6+
7+## a function to replace some strings -- not important how it works for this example.
8+
9+
10+search_replace <- function(df, pattern_search, pattern_replace){
11+ x <- df %>%
12+ mutate(across(where(is.character),
13+ stringr::str_replace_all, pattern = pattern_search,
14+ replacement = pattern_replace))
15+}
16+
17+
18+
19+zz <- paste(seq(10), "%", sep="")
20+
21+df <- tibble(x=letters[1:10], y=c(rep(-1,5), rep(1,5)),
22+ z=zz)
23+
24+df_plot1 <- df %>%
25+ search_replace( "%", "\\\\%" ) ## to render the percentages in latex
26+
27+
28+ll1 <- df_plot1 %>%
29+ kable("latex", booktabs = T, escape = F)
30+
31+
32+
33+
34+
35+
36+
37+
38+
39+
40+writeLines(
41+ c(
42+ "\\documentclass{article}",
43+ "\\usepackage{graphicx}",
44+ "\\usepackage{makecell}",
45+ "\\usepackage{booktabs}",
46+"\\usepackage{colortbl, xcolor}",
47+"\\begin{document}",
48+"\\thispagestyle{empty}",
49+ ll1,
50+ "\\end{document}"
51+ ),
52+ "test1.tex"
53+)
54+
55+
56+
57+
58+
59+
60+
61+
62+
63+
64+tools::texi2pdf("test1.tex", clean = TRUE) ## and everything is fine
65+
66+
67+
68+##now with conditional formatting
69+
70+ll2 <- df %>%
71+ mutate(z = cell_spec(z, "latex",
72+ color = ifelse(y >= 0, "black", "red"))) %>%
73+
74+ kable("latex", booktabs = T, escape = F)
75+
76+
77+
78+
79+writeLines(
80+ c(
81+ "\\documentclass{article}",
82+ "\\usepackage{graphicx}",
83+ "\\usepackage{makecell}",
84+ "\\usepackage{booktabs}",
85+"\\usepackage{colortbl, xcolor}",
86+"\\begin{document}",
87+"\\thispagestyle{empty}",
88+ ll2,
89+ "\\end{document}"
90+ ),
91+ "test2.tex"
92+)
93+
94+
95+
96+
97+
98+
99+
100+
101+tools::texi2pdf("test2.tex", clean = TRUE) ## and the % is no longer rendered correctly
102+
103+
104+