Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 1 | #' Make linebreak in LaTeX Table cells |
| 2 | #' |
Duncan Murdoch | 7897b5f | 2021-12-09 16:33:16 -0500 | [diff] [blame^] | 3 | #' @description This function generates LaTeX code of `makecell` so that users |
Hao Zhu | 5e4dd50 | 2018-04-05 12:01:58 -0400 | [diff] [blame] | 4 | #' can have linebreaks in their table |
| 5 | #' |
| 6 | #' @param x A character vector |
Duncan Murdoch | 7897b5f | 2021-12-09 16:33:16 -0500 | [diff] [blame^] | 7 | #' @param align Choose from "l", "c" or "r". Defaults to "l". |
Hao Zhu | 5e4dd50 | 2018-04-05 12:01:58 -0400 | [diff] [blame] | 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) |
Duncan Murdoch | 7897b5f | 2021-12-09 16:33:16 -0500 | [diff] [blame^] | 17 | if (missing(align)) |
| 18 | align <- "l" |
kbrevoort | c79c5a8 | 2019-08-26 22:44:01 -0400 | [diff] [blame] | 19 | align <- vapply(align, match.arg, 'a', choices = c("l", "c", "r")) |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 20 | if (double_escape) { |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 21 | ifelse(str_detect(x, linebreaker), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 22 | paste0("\\\\makecell[", align, "]{", |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 23 | str_replace_all(x, linebreaker, "\\\\\\\\\\\\\\\\"), "}"), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 24 | x) |
| 25 | } else { |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 26 | ifelse(str_detect(x, linebreaker), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 27 | paste0("\\makecell[", align, "]{", |
Hao Zhu | a17edd0 | 2018-09-15 21:20:44 -0400 | [diff] [blame] | 28 | str_replace_all(x, linebreaker, "\\\\\\\\"), "}"), |
Hao Zhu | 248bbef | 2018-04-02 18:25:14 -0400 | [diff] [blame] | 29 | x) |
| 30 | } |
| 31 | } |
Hao Zhu | 5e4dd50 | 2018-04-05 12:01:58 -0400 | [diff] [blame] | 32 | |
| 33 | linebreak_html <- function(x) { |
| 34 | if (is.numeric(x) | is.logical(x)) return(x) |
| 35 | ifelse(str_detect(x, "\n"), str_replace_all(x, "\n", "<br />"), x) |
| 36 | } |