I have a table which has n and percentages in cells. I would like to divide or multiply each n by a constant, ideally while creating the table.
library(gtsummary)
df <- data.frame(
a=sample(1:4, 10, replace=T),
b=sample(1:4, 10, replace=T),
c=sample(1:4, 10, replace=T)
)
df %>%
tbl_summary()
For example, instead of the first entry being 5 (50%)
, I would like to divide each n by 10, leading to .5 (50%)
.
I’ve tried 1) modifying the table’s data with regular expressions which seems quite involved, and 2) playing unsuccessfully with the statistic term in tbl_summary
. I would appreciate any suggestions.
1
You were concerned about the complexity of your regex approach, but you can do fairly easily with:
ts = tbl_summary(df)
ts$table_body <- ts$table_body %>%
mutate(stat_0 = stringr::str_replace(stat_0,"^\d+",(x) as.numeric(x)/10))
Then ts
renders as:
1
You can use modify_table_body
to do this while creating the table. You could also set up functions to use.
constant <- 10
divide <- (x,y) x/y
multiply <- (x,y) x*y
t1 <- df %>%
tbl_summary() |>
modify_table_body(~ .x %>%
mutate(
stat_0=stringr::str_replace(stat_0,"^\d+", (x)
do.call(divide,
list(as.numeric(x), constant)))))
t2 <- df %>%
tbl_summary() |>
modify_table_body(~ .x %>%
mutate(
stat_0=stringr::str_replace(stat_0, "^\d+", (x)
do.call(multiply,
list(as.numeric(x), constant)))))
tbl_merge(list(t1, t2),
tab_spanner = c("**Divide**", "**Multiply**"))
You could also do it this way:
FUN <- '/'
constant <- 10
df %>%
tbl_summary() |>
modify_table_body(~ .x %>%
mutate(
stat_0=stringr::str_replace(stat_0, "^\d+", (x)
do.call(FUN, list(as.numeric(x), constant))
) ) )