benjaminrich / table1

78 stars 26 forks source link

[Feature Request] label and first statistical parameter in one row #84

Closed Blackfishbox closed 2 years ago

Blackfishbox commented 2 years ago

Hi, is it possible and/or could you implement a way to configure some custom renderer for the labels, so that a label and the first (and only) statistical parameter show up in one row? I only managed to show e.g. the label "Male" with its linebreak and then the statistical parameter "N (%)" like this: photo_2022-06-20_18-48-58 However it would be great to have a label in the same line as the statistical parameter like in this example where the label "Age" is in the same row as "Mean (SD)" etc.: photo_2022-06-20_18-49-03

benjaminrich commented 2 years ago

It is possible. Here is an example:

library(table1)

set.seed(123)

n <- 65

dat <- data.frame(
    group = sample(1:2, n, replace=T),
    age = runif(n, 18, 80),
    wt = exp(rnorm(n, log(70), 0.2)),
    sex = sample(1:2, n, replace=T),
    country = sample(1:5, n, replace=T))

dat$group   <- factor(dat$group,   labels=c("Treatment", "Control"))
dat$sex     <- factor(dat$sex,     labels=c("Male", "Female"))
dat$country <- factor(dat$country, labels=c("UK", "Italy", "Spain", "France", "Germany"))

dat$is_male <- dat$sex == "Male"

label(dat$age)     <- "Age, years,  mean (SD)"
label(dat$wt)      <- "Weight, kg, mean (SD)"
label(dat$is_male) <- "Male, n (%)"
label(dat$country) <- "Country, n (%)"

rndr <- function(x, ...) {
    y <- render.default(x, ...)
    if (is.logical(x)) y[2] else y
}

table1(~ age + wt + is_male + country | group, data=dat,
    render.continuous="Mean (SD)", render=rndr)

image

Blackfishbox commented 2 years ago

Awesome, thank you very much for your quick reply and help! :)