blob: 3bc0d51668eaf16270f85ced2ca93c975b5201f5 [file] [log] [blame]
Hao Zhu248bbef2018-04-02 18:25:14 -04001#' Make linebreak in LaTeX Table cells
2#'
Hao Zhu5e4dd502018-04-05 12:01:58 -04003#' @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 Zhub548aac2018-09-18 13:29:01 -040010#' @param linebreaker Symbol for linebreaks to replace. Default is `\\n`.
Hao Zhu5e4dd502018-04-05 12:01:58 -040011#'
Hao Zhu248bbef2018-04-02 18:25:14 -040012#' @export
Hao Zhua17edd02018-09-15 21:20:44 -040013linebreak <- function(x, align = c("l", "c", "r"), double_escape = F,
14 linebreaker = "\n") {
Hao Zhu248bbef2018-04-02 18:25:14 -040015 if (is.numeric(x) | is.logical(x)) return(x)
Hao Zhu3e0e2b12018-10-23 11:21:29 -040016 x <- as.character(x)
kbrevoortc79c5a82019-08-26 22:44:01 -040017 align <- vapply(align, match.arg, 'a', choices = c("l", "c", "r"))
Hao Zhu248bbef2018-04-02 18:25:14 -040018 if (double_escape) {
Hao Zhua17edd02018-09-15 21:20:44 -040019 ifelse(str_detect(x, linebreaker),
Hao Zhu248bbef2018-04-02 18:25:14 -040020 paste0("\\\\makecell[", align, "]{",
Hao Zhua17edd02018-09-15 21:20:44 -040021 str_replace_all(x, linebreaker, "\\\\\\\\\\\\\\\\"), "}"),
Hao Zhu248bbef2018-04-02 18:25:14 -040022 x)
23 } else {
Hao Zhua17edd02018-09-15 21:20:44 -040024 ifelse(str_detect(x, linebreaker),
Hao Zhu248bbef2018-04-02 18:25:14 -040025 paste0("\\makecell[", align, "]{",
Hao Zhua17edd02018-09-15 21:20:44 -040026 str_replace_all(x, linebreaker, "\\\\\\\\"), "}"),
Hao Zhu248bbef2018-04-02 18:25:14 -040027 x)
28 }
29}
Hao Zhu5e4dd502018-04-05 12:01:58 -040030
31linebreak_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}