Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading