I have a series of summary tables that are identical except for one of the variables. Using kable
I'm trying to create a function that will produce identical tables for every variable and use the input to change the caption, however it's creating two captions per tables.
Sample Code
suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(kableExtra))
table_eye_color <- starwars %>%
dplyr::filter(eye_color %in% c("black", "blue", "yellow", "brown")) %>%
group_by (gender, eye_color) %>%
count () %>%
mutate (n_2 = n + 2) %>%
na.omit (gender) %>%
dplyr::filter (gender != "none")
table_hair_color <- starwars %>%
dplyr::filter(eye_color %in% c("black", "brown", "none", "white")) %>%
group_by (gender, hair_color) %>%
count () %>%
mutate (n_2 = n + 2) %>%
na.omit (gender)%>%
dplyr::filter (gender != "none")
my_kable <- function (df, x){
x <- enquo(x)
table <- df %>%
kable ("latex",
booktabs = TRUE,
linesep = "",
caption = paste0 ("Gender by ", x)) %>%
kable_styling(latex_options = "HOLD_position") %>%
add_header_above(c(" ", " ", "N and N + 2" = 2)) %>%
column_spec(3:4, width = "1cm") %>%
collapse_rows(columns = 1, valign = "middle")
return (table)
}
my_kable(table_eye_color, "Eye Color")
my_kable(table_hair_color, "Hair Colour")
Produces this: