【发布时间】:2020-10-26 20:20:26
【问题描述】:
这是一个患者数据的示例数据集(实际有大约 26k 行)。
library(pivottabler)
library(tables)
library(tidyverse)
df <- tribble(
~Patient, ~Physician, ~Specialty, ~Duration, ~CostWeight,
1, "A", "Family Medicine", 5, 1.4215,
2, "A", "Family Medicine", 7, 1.6463,
3, "B", "Pediatrics", 1, 1.0214,
4, "B", "Pediatrics", 3, 1.2345,
5, "B", "Pediatrics", 6, 6.3243,
6, "C", "Neurology", 10, 2.5104,
7, "D", "Dermatology", 0, 1.0424,
8, "E", "Family Medicine", 2, 1.5234
)
基本上,我正在尝试在 R 中重新创建 Excel 数据透视表,因为这将每月使用不同的数据集进行,最好插入文件并运行代码来获取数据透视表,而不是比手工做。
我想要一个看起来像 this 的表格。
期望的特性:
- 需要每个专业分组的总行数
- 需要总计行
- 可以使用
kable()/kableExtra 包自定义的表
尝试 1
我尝试过使用this example。
tabular(Specialty * (Physician + 1) + 1 ~
(
(Count = Patient) +
(avgDuration = mean(Duration)) +
(avgCostWeight = mean(CostWeight))
),
data = df)
但是,我一直收到错误提示
term2table(rows[[i]], cols[[j]], data, n) 中的错误:重复值:专业和医师”。
尝试 2
我也尝试过使用 this post 的 pivottabler 包。
pt <- df %>%
qpvt(c("Specialty", "Physician"), NULL, c("Discharges" = "n()",
"avgDuration" = "mean(Duration)",
"avgCostWeight" = "mean(CostWeight)")
)
pt$evaluatePivot()
df <- pt$asDataFrame()
df %>%
kbl()
但是,输出不太理想,因为它将 Specialty 和 Physician 列连接到 one。
有人有线索吗?
【问题讨论】:
标签: r r-markdown pivot-table tabular