Search code examples
rfunctionexpressionflextable

Flextable Selectors: Making a function for the i and j arguments


As noted in 2.4 selectors of the flextable vignette, often we would want to conditionally add formatting to a flextable. The following example is from the flextable vignette: https://ardata-fr.github.io/flextable-book/design.html

library(flextable)
dat <- head(ggplot2::diamonds, n = 10)
ft <- qflextable(dat) 

color(ft,
~ price < 330, color = "orange", ~ price + x + y + z 
)  

color(
  ft,
  i = ~ cut %in% "Premium", 
  j = ~ x + y, 
color = "red"
)

As the dataset varies, I want to make the selection of cut above as a function.

#'@param x A flextable
#'@param t Text within the dataset x
f <- function(x, t)  x %>% color(i = ~ cut %in% t, j = ~ x + y,  color = "red")

f(ft, "Premium")
# Error in match(x, table, nomatch = 0L) : 
'match' requires vector arguments

I wonder how the flexible selection handle arguments passed into expression. Is there a way to make a function that works similar to adding the text itself.

Exploring a little deeper, a function like color passes the condition to internal get_row_id() to internal get_i_from_formula(). The error occurs in evaluating the call


Solution

  • As stefan points out your formula is not capturing the argument t (instead it assumes it's refering to the function t.

    Alternatively, you can inject the parameter with rlang:

    f <- function(x, t) rlang::inject(
      x %>% color(i = ~ cut %in% !!t, j = ~ x + y,  color = "red"))
    
    f(ft, "Premium")