Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 1 | #' Make linebreak in LaTeX Table cells |
| 2 | #' |
Hao Zhu | 5e4dd50 | 2018-04-05 12:01:58 -0400 | [diff] [blame] | 3 | #' @description This function generate LaTeX code of `makecell` so that users |
| 4 | #' can have linebreaks in their table |
| 5 | #' |
| 6 | #' @param x A character vector |
| 7 | #' @param align Choose from "l", "c" or "r" |
| 8 | #' @param double_escape Whether special character should be double escaped. |
| 9 | #' Default is FALSE. |
Hao Zhu | b548aac | 2018-09-18 13:29:01 -0400 | [diff] [blame] | 10 | #' @param linebreaker Symbol for linebreaks to replace. Default is `\\n`. |
Hao Zhu | 5e4dd50 | 2018-04-05 12:01:58 -0400 | [diff] [blame] | 11 | #' |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 12 | #' @export |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 13 | linebreak <- function(x, align = c("l", "c", "r"), double_escape = F, |
| 14 | linebreaker = "\n") { |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 15 | if (is.numeric(x) | is.logical(x)) return(x) |
Hao Zhu | 3e0e2b1 | 2018-10-23 11:21:29 -0400 | [diff] [blame] | 16 | x <- as.character(x) |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 17 | align <- match.arg(align, c("l", "c", "r")) |
| 18 | if (double_escape) { |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 19 | ifelse(str_detect(x, linebreaker), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 20 | paste0("\\\\makecell[", align, "]{", |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 21 | str_replace_all(x, linebreaker, "\\\\\\\\\\\\\\\\"), "}"), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 22 | x) |
| 23 | } else { |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 24 | ifelse(str_detect(x, linebreaker), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 25 | paste0("\\makecell[", align, "]{", |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 26 | str_replace_all(x, linebreaker, "\\\\\\\\"), "}"), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 27 | x) |
| 28 | } |
| 29 | } |
Hao Zhu | 5e4dd50 | 2018-04-05 12:01:58 -0400 | [diff] [blame] | 30 | |
| 31 | linebreak_html <- function(x) { |
| 32 | if (is.numeric(x) | is.logical(x)) return(x) |
| 33 | ifelse(str_detect(x, "\n"), str_replace_all(x, "\n", "<br />"), x) |
| 34 | } |