if (FALSE) {
library(openxlsx)
data(mtcars)
# add labels to dataset
mtcars = apply_labels(mtcars,
mpg = "Miles/(US) gallon",
cyl = "Number of cylinders",
disp = "Displacement (cu.in.)",
hp = "Gross horsepower",
drat = "Rear axle ratio",
wt = "Weight (lb/1000)",
qsec = "1/4 mile time",
vs = "Engine",
vs = c("V-engine" = 0,
"Straight engine" = 1),
am = "Transmission",
am = c("Automatic" = 0,
"Manual"=1),
gear = "Number of forward gears",
carb = "Number of carburetors"
)
# create table with caption
mtcars_table = cross_cpct(mtcars,
cell_vars = list(cyl, gear),
col_vars = list(total(), am, vs)
) %>%
set_caption("Table 1")
wb = createWorkbook()
sh = addWorksheet(wb, "Tables")
# export table
xl_write(mtcars_table, wb, sh)
saveWorkbook(wb, "table1.xlsx", overwrite = TRUE)
## quick export
xl_write_file(mtcars_table, "table1.xlsx")
## custom cells formatting
wb = createWorkbook()
sh = addWorksheet(wb, "Tables")
# we want to mark cells which are greater than total column
my_formatter = function(tbl){
greater_than_total = tbl[,-1]>tbl[[2]]
which(greater_than_total, arr.ind = TRUE)
}
# export table
xl_write(mtcars_table, wb, sh,
additional_cells_formats = list(
list(my_formatter, createStyle(textDecoration = "bold", fontColour = "blue"))
)
)
saveWorkbook(wb, "table_with_additional_format.xlsx", overwrite = TRUE)
## automated report generation on multiple variables with the same banner
banner = with(mtcars, list(total(), am, vs))
# create list of tables
list_of_tables = lapply(mtcars, function(variable) {
if(length(unique(variable))<7){
cro_cpct(variable, banner) %>% significance_cpct()
} else {
# if number of unique values greater than seven we calculate mean
cro_mean_sd_n(variable, banner) %>% significance_means()
}
})
wb = createWorkbook()
sh = addWorksheet(wb, "Tables")
# export list of tables with additional formatting
xl_write(list_of_tables, wb, sh,
# remove '#' sign from totals
col_symbols_to_remove = "#",
row_symbols_to_remove = "#",
# format total column as bold
other_col_labels_formats = list("#" = createStyle(textDecoration = "bold")),
other_cols_formats = list("#" = createStyle(textDecoration = "bold")),
)
saveWorkbook(wb, "report.xlsx", overwrite = TRUE)
}
Run the code above in your browser using DataLab