benjaminrich / table1

79 stars 26 forks source link

Combine columns for longitudinal data #49

Closed samstewart11 closed 3 years ago

samstewart11 commented 3 years ago

Is there a way to combine the presentation of multiple columns? I'm trying to summarize some longitudinal data, and I would like to combine them in consecutive rows with a single title. In the dummy example below I have four separate titles - I'd like a single title called "meas" and then 4 consecutive rows of mean (SD) - some kind of title on each row would be helpful as well. Is that possible in the current implementation?

n=100
set.seed(42)
dumDat = data.frame(
  surgery = rbinom(n,1,0.5),
  week01.meas = runif(n,0,1),
  week02.meas = runif(n,0.2,1),
  week03.meas = runif(n,0.4,1),
  week04.meas = runif(n,0.6,1)
)
my.render.cont <- function(x) {
  with(stats.apply.rounding(stats.default(x), digits=2), c("",
                                                           "Mean (SD)"=sprintf("%s (%s)", MEAN, SD)))
}
table1(~.,data=dumDat,render.continuous = my.render.cont)
benjaminrich commented 3 years ago

Maybe not exactly what you want, but you can trick it to give what I think you are asking for like this:

strata <- list(Overall=dumDat)

labels <- list(
    variables=list(
        surgery = render.varlabel(setLabel(NA, "Surgery")),
        dummy = render.varlabel(setLabel(NA, "Measurement (Mean (SD))")),
        week01.meas = '<span style="padding-left: 2ex; font-weight: normal;">Week 1</span>',
        week02.meas = '<span style="padding-left: 2ex; font-weight: normal;">Week 2</span>',
        week03.meas = '<span style="padding-left: 2ex; font-weight: normal;">Week 3</span>',
        week04.meas = '<span style="padding-left: 2ex; font-weight: normal;">Week 4</span>' 
))

render <- function(x, name, ...) {
    r <- render.default(x, name, ...)
    if (name=="dummy") {
        ""
    } else if (grepl("^week.*\\.meas$", name)) {
        r["Mean (SD)"]
    } else {
        r
    }
}

table1(strata, labels, render=render)

image

samstewart11 commented 3 years ago

That's an interesting idea, thanks, I'll look into it

benjaminrich commented 3 years ago

I don't have the big picture of what you are trying to do, but table1 might not be the most suitable tool for this (although there are some workarounds, as I've pointed out). You might want to look at my latest package, ttt (CRAN | GitHub). Note that ttt is NOT intended as a replacement for table1, it serves a different purpose.