I have claims level data for health care consumption. I would like to create a journal quality table (exportable into Word) similar to the one below. That is I would like to calculate the price (and S.D. in parenthesis) of all DRGs per year.
Is there a package that will do this for me?
Here's a sample rmarkdown
document that renders a table to Word, PDF, or html. The code uses kable
and kableExtra
for html and PDF tables, and flextable
for Word tables. The Vignettes for these packages (see the links above) provide details on how to customize table formatting.
Some other resources for generating tables in R are here and here.
---
title: "My Report"
output:
word_document: default
pdf_document: default
html_document:
df_print: paged
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(flextable)
library(officer)
library(tidyverse)
```
```{r}
# Fake data
set.seed(2)
d = data.frame(years = sample(2014:2016, 100, replace=TRUE),
drg = sample(paste0("DRG",1:4), 100, replace=TRUE),
value=runif(100, 0, 10))
# Set up table data
tab = d %>%
group_by(drg, years) %>%
summarise(mean = sprintf("%1.2f", mean(value)),
sd = sprintf("(%1.2f)", sd(value))) %>%
pivot_longer(cols=c(mean, sd), names_to="var") %>%
pivot_wider(names_from=years, values_from=value) %>%
select(-var)
names(tab)[1] = " "
```
```{r}
# Print latex, html or Word table, depending on output type
out = ifelse(is_html_output(), "html",
ifelse(is_latex_output(), "latex", "word"))
if(out != "word") {
kable(tab, format=out, booktabs=ifelse(out=="latex", TRUE, FALSE)) %>%
kable_styling() %>%
collapse_rows(columns=1)
} else (
tab %>%
flextable() %>%
merge_v(j=" ") %>%
theme_vanilla() %>%
hline(i = seq(1,nrow(tab),2), j=2:4, border=fp_border(color="white")) %>%
height(height=0.25, part="body")
)
```
Here's what the Word output looks like: