gt
gt copied to clipboard
Using cur_column() as a way to reference another dataframe or list in summary rows.
I am trying to create summary rows with reference to another data source.
Let's say we have df results that I want to print with summary rows and a dataframe containing different reference values for each column:
results <- data.frame(level = c("LQC", "LQC", "LQC", "LQC", "LQC", "LQC", "LQC", "LQC", "LQC", "HQC", "HQC", "HQC", "HQC", "HQC", "HQC", "HQC", "HQC", "HQC"),
source = c("A", "A", "A", "B", "B", "B", "C", "C", "C", "A", "A", "A", "B", "B", "B", "C", "C", "C"),
val_A = c(30.1822, 33.0850, 32.2722, 27.7168, 29.1946, 29.1808, 33.1962, 32.6243, 31.7900, 1799.5074, 2012.0351, 2054.0858, 1956.2820, 1990.6278, 2081.3730, 1955.4075, 2073.8068, 2076.9238),
val_B = c(3.6880, 3.8021, 3.5833, 3.4146, 2.7805, 3.1428, 2.9596, 4.0376, 3.9008, 362.4901, 331.9178, 337.8255, 324.2157, 336.1455, 342.8927, 317.3914, 334.1520, 338.8625))
reference <- data.frame(level = c("LQC", "HQC"),
val_A = c(30, 2000),
val_B = c(3, 400))
I need summary rows grouped by level and source. In summary I need accuracy, which will be: mean of the group divided by reference value from different df (or list) multiplied by 100
My idea was to make separate tables for each level and to use cur_column()
like this:
results_LQC <- results |>
filter(level == "LQC") |>
select(-level)
reference_LQC <- reference |>
filter(level == "LQC") |>
select(-level)
res_LQC_tab <- results_LQC |>
group_by(source) |>
gt()|>
summary_rows(columns = matches("val_"),
fns = list(id = "mean", label = "Mean", fn = "mean"),
fmt = ~ fmt_number(., decimals = 2)) |>
summary_rows(columns = matches("val_"),
fns = list(id = "acc", label = "Accuracy", fn = ~mean(.)/reference_LQC[[cur_column()]]*100),
fmt = ~ fmt_number(., decimals = 2, pattern = "{x}%"))|>
summary_rows(columns = matches("val_"),
fns = list(id = "cv", label = "CV", fn = ~sd(.)/mean(.)*100),
fmt = ~ fmt_number(., decimals = 2, pattern = "{x}%"))|>
fmt_number(columns = matches("val_"),
decimals = 2)
Unfortunately, cur_column
does not work in gt.
I think it would be useful to have an easy way to reference data from another df when creating summary rows. And to make this reference dependent on the column being summarized.
Ideal solution would also allow to reference row according to the group that is summarized...
Regards, Radek