knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(tfrmt)
library(dplyr)

Aside from R code, tfrmt objects can be represented as machine-readable metadata in JSON format. This enables users to save formatting metadata to a database, or alternatively import templates stored as JSON files. There are several utilities available for seamless translation between tfrmt and JSON.

tfrmt to JSON

A tfrmt object can be converted to JSON using the tfrmt_to_json function. Suppose we have a basic tfrmt:

template_tfrmt <- tfrmt(
  group = grp,
  label = label,
  column = column,
  param = param,
  value=value,
  body_plan = body_plan(
    frmt_structure(group_val = ".default", 
                        label_val = ".default", 
                        frmt("xx.x")))
  ) 
template_tfrmt %>% print_mock_gt()

We can pass this through tfrmt_to_json to convert to JSON metadata.

template_tfrmt %>%
  tfrmt_to_json()

This JSON can optionally be saved to a file by providing a file path as the second argument to the function:

tfrmt(
  group = grp,
  label = label,
  column = column,
  param = param,
  value=value,
  body_plan = body_plan(
    frmt_structure(group_val = ".default", 
                        label_val = ".default", 
                        frmt("xx.x")))
  ) %>%
  tfrmt_to_json(path = "template.JSON")

JSON to tfrmt

If a JSON file already exists, users can import this into R.

template_json <- tfrmt(
  group = grp,
  label = label,
  column = column,
  param = param,
  value=value,
  title= 'mytitle',
  body_plan = body_plan(
    frmt_structure(group_val = ".default", 
                        label_val = ".default", 
                        frmt("xx.x")))
  )
template_json <- json_to_tfrmt(path = "template.JSON")

Once available in the R session, users can optionally build on this template as needed.

template_json %>% 
  layer_tfrmt(
    tfrmt(title = "Custom title")
  ) %>% 
  print_mock_gt()


GSK-Biostatistics/tlang documentation built on Dec. 11, 2024, 11:16 a.m.