Reputation: 37
I've created a table in R to serve as a results table for other analyses I've done.
The table runs fine, but I'd like each column to also show that value as a percentage of the total value (i.e. the number provided in the n column below) - something similar to how tbl_summary achieves this - for example, see how in the table the percentage appears beside each value: https://www.danieldsjoberg.com/gtsummary/articles/tbl_summary.html
I know this is not possible with tbl_summary without going back and creating individual columns for each result I've done and making fairly significant alterations to how I've run this analysis thus far, but would anyone know if this would be possible to achieve another way?
measure <- c("Chalk", "Cheese", "Apples", "Pears", "Beach")
n <- c(49, 45, 43, 41, 40)
improved_total <- c(19, 7, 24, 16, 16)
improved_reliable <- c(7, 1, 0, 2, 4)
much <- c(7, 0, 13, 9, 7)
minimally <- c(12, 7, 11, 7, 9)
unchanged <- c(23, 29, 7, 16, 14)
unchanged_reliable <- c(42, 44, 43, 39, 36)
deteriorated <- c(7, 9, 12, 9, 10)
deteriorated_reliable <- c(0, 0, 0, 0, 0)
tr_rc_tib <- tibble::tibble(measure, n,
improved_total, improved_reliable, much,
minimally, unchanged, unchanged_reliable,
deteriorated, deteriorated_reliable) %>%
knitr::kable(
format = "html",
col.names = c("Measure", "*n*", "Total", "RC",
"Mh", "My", "Total", "RC", "Total",
"RC")) %>%
kableExtra::add_header_above(c(" " = 1,
"Total"= 1, "I" = 4, "U" = 2,
"D" = 2)) %>%
kableExtra::kable_classic_2(
lightable_options = "striped",
full_width = FALSE,
html_font = "Times New Roman",
font_size = 12
)
tr_rc_tib
Thanks in advance for taking a look!
Upvotes: 1
Views: 579
Reputation: 634
I might have found a way which solves your probleme with the mutate()
functions (link)
First you need to create a function to modify the numerical columns:
get_smry_percent <- function(x){
if (is.numeric(x)){
# Get the percent for each valule (with 0 digits)
x_percent <- round(100*x/sum(x), digits = 0)
# Get the output
x <- paste0(x, " (", x_percent, "%)")
}
return(x)
}
Then you can add the line mutate_all(get_smry_percent) %>%
to transforme every numerical column into the format you wanted.
# Plot table:
tr_rc_tib <- tibble::tibble(measure, n,
improved_total, improved_reliable, much,
minimally, unchanged, unchanged_reliable,
deteriorated, deteriorated_reliable) %>%
mutate_all(get_smry_percent) %>%
knitr::kable(
format = "html",
col.names = c("Measure", "*n*", "Total", "RC",
"Mh", "My", "Total", "RC", "Total",
"RC")) %>%
kableExtra::add_header_above(c(" " = 1,
"Total"= 1, "I" = 4, "U" = 2,
"D" = 2)) %>%
kableExtra::kable_classic_2(
lightable_options = "striped",
full_width = FALSE,
html_font = "Times New Roman",
font_size = 12
)
tr_rc_tib
You could also replace the mutate_all()
by mutate_at(c("n", "improved_total"), get_smry_percent)
just to modify the columns selected
Upvotes: 1