Search code examples
rflextable

How to refer to a column when creating flextable using `tabulator`, which includes `@` symbol in `col_keys`


I created a flextable using tabulator(), such as

Grp <- LETTERS[1:3]
Display <- c("Good", "Bad")
AgeGrp = c("00-11", "12-17")

dt <- expand.grid(Grp = Grp, Display = Display, AgeGrp = AgeGrp)
dt$outcome <- runif(12)

myformat <- function(z) {
    x <- sprintf("%.3f", z)
    x[is.na(z)] <- ""
    x
}

ft_dt <- tabulator(
  x = dt, rows = c("Grp", "Display"),
  columns = "AgeGrp",
  `Age` = as_paragraph(as_chunk(outcome, formatter = myformat))
) 

ft <- as_flextable(ft_dt)

This would result in the col_keys such as "00-11@Age".

I would also like to reformat the values conditionally, as some to percentage, and some keeps as numeric.

However, the following code won't work

compose(ft, i = ~Display=="Good", j = "00-11@Age", 
         value = as_paragraph(
           sprintf("%.0f", `00-11@Age`)
         ))

compared to the example below

ft_1 <- flextable(head(cars, n = 5), col_keys = c("speed", "dist"))
compose(
  x = ft_1, j = "speed",
  i = ~ dist > 9,
  value = as_paragraph(
    sprintf("%.3f%%", speed)
  )
)

How could I refer to a column name with @ in it?


Solution

  • The error we obtain is as follows:

    invalid format '%.0f'; use format %s for character objects
    

    The problem here is that you're using the wrong column name, but that's easy to fix.

    The tabulator_colnames() function will display the names that can be manipulated for conditional formatting. For example:

    tabulator_colnames(ft_dt, columns = "outcome")
    [1] "outcome@00-11" "outcome@12-17"
    

    Here we need to format the displayed column named "00-11@Age" but using the value stored in the "outcome@00-11" column, which is not displayed (but stored).

    compose(ft, i = ~Display=="Good", j = "00-11@Age", 
            value = as_paragraph(
              sprintf("%.0f", `outcome@00-11`)
            ))
    

    enter image description here