科学期刊 table 每年变量平均值与 S.D

Scientific journal table of variable mean per year with S. D

我有医疗保健消费的索赔水平数据。我想创建一个类似于下面的期刊质量 table(将 table 导出到 Word)。那就是我想计算每年所有 DRG 的价格(和 S.D. 在括号中)。

是否有可以为我执行此操作的软件包?

这是一个示例 rmarkdown 文档,可将 table 呈现为 Word、PDF 或 html。代码使用 kablekableExtra for html and PDF tables, and flextable for Word tables。这些包的 Vignettes(参见上面的链接)提供了有关如何自定义 table 格式的详细信息。

在 R 中生成 table 的其他一些资源是 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")
)
```

这是 Word 输出的样子: