blob: 4fcfa8bd257f07bb1de21dafd95e1b97fa478af8 [file] [log] [blame]
Dan Chaltiel075db092020-08-03 22:18:33 +02001#' Remove columns
2#'
3#' @param kable_input Output of [knitr::kable()] with format specified
4#' @param columns A numeric value or vector indicating in which column(s) rows need to be removed
5#'
6#' @export
7#'
8#' @examples
9#' mtcars %>%
10#' kable() %>%
11#' remove_column(2:3)
Dan Chaltiel9e83d8f2020-08-03 22:46:35 +020012remove_column <- function (kable_input, columns) {
Dan Chaltiel075db092020-08-03 22:18:33 +020013 kable_format <- attr(kable_input, "format")
14 if (!kable_format %in% c("html", "latex")) {
15 warning("Please specify format in kable. kableExtra can customize either ",
16 "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
17 "for details.")
18 return(kable_input)
19 }
20 if (kable_format == "html") {
21 return(remove_column_html(kable_input, columns))
22 } else if (kable_format == "latex") {
23 stop("Removing columns was not implemented for latex kables yet")
24 }
25}
26
27remove_column_html <- function (kable_input, columns) {
28 kable_attrs <- attributes(kable_input)
29 kable_xml <- kable_as_xml(kable_input)
30 kable_tbody <- xml_tpart(kable_xml, "tbody")
31 kable_thead <- xml_tpart(kable_xml, "thead")
32
33 cell_topleft <- xml2::xml_child(kable_thead, 1) %>%
34 xml2::xml_child(1) %>%
35 xml2::xml_text() %>%
36 stringr::str_trim()
37 has_rownames <- cell_topleft==""
38 if(has_rownames) columns <- columns+1
39
40 body_rows <- xml2::xml_length(kable_tbody)
41 for(i in 1:body_rows){
42 for(j in columns){
43 target_row <- xml2::xml_child(kable_tbody, i)
44 target_cell <- xml2::xml_child(target_row, j)
45 xml2::xml_remove(target_cell)
46 }
47 }
48 target_row_head <- xml2::xml_child(kable_thead, 1)
49 for(j in columns){
50 target_cell_head <- xml2::xml_child(target_row_head, j)
51 xml2::xml_remove(target_cell_head)
52 }
53 out <- as_kable_xml(kable_xml)
54 attributes(out) <- kable_attrs
55 if (!"kableExtra" %in% class(out))
56 class(out) <- c("kableExtra", class(out))
57
58 return(out)
59}