## Example 1: Formatting List - Column Type ##
# Set up data
v1 <- c(Sys.Date(), Sys.Date() + 30, Sys.Date() + 60)
# Create formatting list
fl1 <- flist("%B", "The month is: %s")
# Apply formatting list to vector
fapply(v1, fl1)
# [1] "The month is: October" "The month is: November" "The month is: December"
## Example 2: Formatting List - Row Type ordered ##
# Set up data
# Notice each row has a different data type
l1 <- list("A", 1.263, as.Date("2020-07-21"),
"B", 5.8732, as.Date("2020-10-17"))
# These formats will be recycled in the order specified
fl2 <- flist(type = "row",
c(A = "Label A", B = "Label B"),
"%.1f",
"%d%b%Y")
fapply(l1, fl2)
# [1] "Label A" "1.3" "21Jul2020" "Label B" "5.9" "17Oct2020"
## Example 3: Formatting List - Row Type with lookup ##
#' # Create formatting list
fl3 <- flist(type = "row",
DEC1 = "%.1f",
DEC2 = "%.2f",
PCT1 = "%.1f%%")
# Set up data
df <- data.frame(CODE = c("DEC1", "DEC2", "PCT1", "DEC2", "PCT1"),
VAL = c(41.258, 62.948, 12.125, 65.294, 15.825))
# Assign lookup
fl3$lookup <- df$CODE
# Apply Formatting List
fapply(df$VAL, fl3)
# [1] "41.3" "62.95" "12.1%" "65.29" "15.8%"
## Example 4: Formatting List - Values with Units ##
#' # Create formatting list
fl4 <- flist(type = "row",
BASO = "%.2f x10(9)/L",
EOS = "%.2f x10(9)/L",
HCT = "%.1f%%",
HGB = "%.1f g/dL")
# Set up data
df <- data.frame(CODE = c("BASO", "EOS", "HCT", "HGB"),
VAL = c(0.02384, 0.14683, 40.68374, 15.6345))
# Assign lookup
fl4$lookup <- df$CODE
# Apply Formatting List
df$VALC <- fapply(df$VAL, fl4)
# View results
df
# CODE VAL VALC
# 1 BASO 0.02384 0.02 x10(9)/L
# 2 EOS 0.14683 0.15 x10(9)/L
# 3 HCT 40.68374 40.7%
# 4 HGB 15.63450 15.6 g/dL
Run the code above in your browser using DataLab