kaz-yos / tableone

R package to create "Table 1", description of baseline characteristics with or without propensity score weighting
https://cran.r-project.org/web/packages/tableone/index.html
218 stars 41 forks source link

Output of summary.TableOne as data.frame? #60

Open arupakaa opened 4 years ago

arupakaa commented 4 years ago

Thank you for such excellent work.

Simple question: how can we save summary.TableOne output as DF? It doesn't seem to work the same as the print.TableOne wrt as.data.frame.

Any help/ideas are very much appreciated.

akarito commented 3 years ago

I found a code from kaz-yos's gists.

library(openxlsx)
tableone_mat_to_data_frame <- function(mat) {
  bind_cols(data_frame(Variable = rownames(mat)),
            as_data_frame(mat))
}

###  Write a xlsx file
write_tableone_mat_to_xlsx <- function(tableone_mat, file) {
  ## Create a workbook object with one sheet
  ## https://rdrr.io/cran/openxlsx/man/setColWidths.html
  wb <- createWorkbook()
  addWorksheet(wb, sheetName = "1")

  ## Write data frame data to the workbook object
  writeData(wb, sheet = 1, x = tableone_mat_to_data_frame(tableone_mat))

  ## Fix column width automatically
  setColWidths(wb, sheet = 1, cols = seq_len(ncol(tableone_mat)), widths = "auto")

  ## Format the variable name column
  ## https://rdrr.io/cran/openxlsx/man/createStyle.html
  varname_style <- createStyle(halign = "left", valign = "center")
  addStyle(wb, sheet = 1, style = varname_style, rows = seq_len(nrow(tableone_mat) + 1), cols = 1, gridExpand = TRUE)

  ## Format all other columns
  varval_style <- createStyle(halign = "center", valign = "center")
  addStyle(wb, sheet = 1, style = varval_style,  rows = seq_len(nrow(tableone_mat) + 1), cols = seq_len(ncol(tableone_mat))[-1], gridExpand = TRUE)

  ## Save to a file
  saveWorkbook(wb, file = file, overwrite = TRUE)
}

but I couldn't figure out what "tableone_mat" is mean?