Non-standard Applications of ksformat for Clinical Trials and Other Tasks
1 Overview
ksformat is usually described as a SAS PROC FORMAT-like tool for ordinary value-to-label lookup. In practice, the package is useful in places where a clinical trial workflow needs more than a plain dictionary:
protocol-defined visit windows
subject- or arm-specific bucketing rules
composite keys built from multiple columns
reverse lookups for data cleaning and QC
report-ready numeric display for listings and summaries
This article shows a few non-standard uses that come up in clinical trials and adjacent data tasks.
2 1. Protocol windows and subject-specific buckets
A common clinical-trials task is mapping visit-day values into protocol-defined windows. The same idea extends to arm-specific rules, where one stratum has a slightly different window structure from another.
Clinical trial data often uses multi-column logic: lab category + test code + unit, or population + analysis flag + visit type. fputk() can build a lookup from multiple fields without manually concatenating in the analysis step.
finputk() is helpful when raw labels must be normalized back to codes. In clinical programming, that makes it suitable for QC checks, mapping vendor text, and validating reviewer-facing labels.
finput(fmap(paste(c("PLACEBO", "DRUG A", "DRUG B"), c("PBO", "A50", "B100"), sep ="|"),c(1L, 2L, 3L) ),target_type ="integer",name ="trt_code_inv")#> KS Invalue: trt_code_inv#> Target Type: integer #> Mappings:#> PLACEBO|PBO => 1#> DRUG A|A50 => 2#> DRUG B|B100 => 3trt_df <-tibble(ARMN =c("PLACEBO", "DRUG A", "DRUG B", "UNKNOWN"),TRTCD =c("PBO", "A50", "B100", "X")) |>mutate(TRTSEQ =finputk(ARMN, TRTCD, invalue_name ="trt_code_inv"))trt_df#> # A tibble: 4 × 3#> ARMN TRTCD TRTSEQ#> <chr> <chr> <int>#> 1 PLACEBO PBO 1#> 2 DRUG A A50 2#> 3 DRUG B B100 3#> 4 UNKNOWN X NA
Typical uses include:
deriving internal codes from decoded labels in QC datasets
validating data entry against controlled terminology
reconciling spreadsheet exports back to source codes
5 4. Report-ready numeric formatting
ksformat can also be used where report output needs consistent numeric presentation. This is not a lookup table; it is a pattern-driven formatter.
fnew("$%,.2f", type ="numeric", name ="currency")fnew("%.1f%%", type ="numeric", name ="pct")summary_df <-tibble(metric =c("Cost", "Response rate"),raw =c(1234.56, 0.153)) |>mutate(display =c(fputn(raw[1], "currency"), fputn(raw[2] *100, "pct")))summary_df#> # A tibble: 2 × 3#> metric raw display #> <chr> <dbl> <chr> #> 1 Cost 1235. $1,234.56#> 2 Response rate 0.153 15.3%
Same result could be achieved using expression labels, but in base R, sprintf() itself does not support thousands separators such as commas. We can use formatC for the formatting purposes. Pattern-driven formatter looks simplier for such case.
ad hoc review tables where consistent display matters
6 5. Bucketing dates into operational periods
Clinical teams often work with periods such as screening, treatment, follow-up, and analysis cut-offs. date_range and datetime_range let you keep those rules in one place instead of duplicating them in ad hoc code.
fparse(text ='VALUE study_period (date_range) [2024-01-01, 2024-02-01) = "Screening" [2024-02-01, 2024-06-01) = "Treatment" [2024-06-01, HIGH] = "Follow-up" .missing = "No date";')obs_dates <-as.Date(c("2024-01-15", "2024-03-10", "2024-07-01", NA))tibble(date = obs_dates,period =fput(obs_dates, "study_period"))#> # A tibble: 4 × 2#> date period #> <date> <chr> #> 1 2024-01-15 Screening#> 2 2024-03-10 Treatment#> 3 2024-07-01 Follow-up#> 4 NA No date
7 6. Text generation for listings and narratives
Expression labels make ksformat useful for building small text fragments in reports. In clinical settings, that can be handy for reviewer comments, summary phrases, or footnotes.
Numeric display formatting now has its own parser syntax. Put the pattern in the VALUE header and keep the block otherwise empty except for optional .missing / .other directives.
fparse(text ='VALUE currency (numeric, pattern: "$%,.2f") .missing = "NO DATA";VALUE pct (numeric, pattern: "%.1f%%");')tibble(raw =c(1234.56, -7890.12, 0, NA),currency =fputn(c(1234.56, -7890.12, 0, NA), "currency"),pct =fputn(c(0, 12.3, -4.5, NA), "pct"))#> # A tibble: 4 × 3#> raw currency pct #> <dbl> <chr> <chr>#> 1 1235. $1,234.56 0.0% #> 2 -7890. -$7,890.12 12.3%#> 3 0 $0.00 -4.5%#> 4 NA NO DATA <NA>
9.5 Range formats
Range formats are expressed with interval notation. The same syntax works for numeric, date_range, and datetime_range blocks.
When ranges overlap, the first matching range in declaration order wins — exactly the order the entries are written, top-down. No warning is emitted for overlaps, so keep the intended precedence explicit in the definition: put the specific (narrow) ranges before the general (wide) ones. To collect all matching labels instead of the first one, create the format with multilabel = TRUE (or an fparse(numeric, multilabel) header) and use fput_all().
Ranges are tried top-down in the order they are written; the first range that contains the value decides the label, and later (even narrower) ranges never get a chance. Keep the specific buckets above the general ones — a wide catch-all declared first shadows everything it covers:
The first block yields "Mild" "Severe" "Abnormal (any grade)"; the second — with the wide range declared first — collapses everything to "Abnormal (any grade)". No warning is emitted for overlaps, so precedence belongs to the definition itself. When several labels are wanted for one value, make them explicit: declare the format multilabel and collect all matches with fput_all():
A note on key text: under type = "auto", a key becomes a range spec only when it actually parses as one. Plain text keys that merely happen to contain a comma ("San Francisco, CA", "Yes, unknown") stay character keys; a thousands-style key like "1,000" is flagged at creation and treated as discrete. Prefer explicit type = "character" for such mappings.
9.6 Stratified range formats
stratified_range combines a stratum with an inner range. The parser accepts the friendly STRATUM|[low, high) form.
fnew() remains the most concise way to create a report-formatting object when you already know you want a display pattern. fparse() is useful when the rule needs to be stored as text, versioned in a spec, or generated from another tool.
fnew("$%,.2f", type ="numeric", name ="currency_direct")fputn(c(1234.56, -7890.12, 0), "currency_direct")#> [1] "$1,234.56" "-$7,890.12" "$0.00"
10 Conclusion
ksformat is not limited to simple code-to-label dictionaries. In clinical trials it can also serve as a compact rule engine for visit windows, composite keys, reverse mappings, report formatting, and small narrative fragments. That makes it useful anywhere repeated conditional logic would otherwise be spread across scripts, spreadsheets, or one-off helper functions.