Here is a sample dataset of patient data (the actual one has ~26k rows).
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
)
Basically, I'm trying to recreate Excel pivot tables in R since this will be on a monthly basis with a different dataset, and it would be great to just plug in the file and run the code to get the pivot tables rather than doing it by hand.
I want a table that looks like this.
Desired characteristics:
- Need the total row for each Specialty grouping
- Need the grand total row
- Table that can be customized using
kable()
/kableExtra package
Attempt 1
I've tried using this example.
tabular(Specialty * (Physician + 1) + 1 ~
(
(Count = Patient) +
(avgDuration = mean(Duration)) +
(avgCostWeight = mean(CostWeight))
),
data = df)
However, I keep getting an error saying
Error in term2table(rows[[i]], cols[[j]], data, n) : Duplicate values: Specialty and Physician".
Attempt 2
I have also tried using the pivottabler package using this post.
pt <- df %>%
qpvt(c("Specialty", "Physician"), NULL, c("Discharges" = "n()",
"avgDuration" = "mean(Duration)",
"avgCostWeight" = "mean(CostWeight)")
)
pt$evaluatePivot()
df <- pt$asDataFrame()
df %>%
kbl()
However, the output is less than desirable since it concatenates the Specialty and Physician columns into one.
Does anybody have any clues?