flextable in a function with a vector of strings

Probably related to this: Using Flextable in a Function - RStudio Community, but passing in a string of vectors. I tried a few things, but couldn't figure it out. Any ideas?

library(tidyverse)
library(flextable)

df <- iris %>% 
  group_by(Species) %>% 
  slice(1)

# this works -------
df %>% 
  flextable(theme_fun = flextable::theme_box) %>% 
  bg(bg = "#f0f0f0", i = ~Species %in% c("setosa", "versicolor"))


# function -------
ft <- function(dataset, values){
  dataset %>% 
    flextable(theme_fun = flextable::theme_box) %>% 
    bg(bg = "#f0f0f0", i = ~Species %in% values)
  
}

# this doesn't -----------------
ft(df, c("setosa", "versicolor"))

Error in Species %in% values : object 'values' not found

Hi @williaml ,

You are correct that it is related to the linked thread Using Flextable in a Function - RStudio Community.

I passed your species formula to a new variable in the function, and called it in the bg() function. Although for this to work I had to pass the list to a variable first, then use that variable in quotes when using the formula.

# function -------
ft <- function(dataset, values) {
  test_formula <- as.formula(paste0("~Species %in%", values)) # create the formula
  print(test_formula) # also printed it just to check
  dataset %>% 
    flextable(theme_fun = flextable::theme_box) %>% 
    bg(bg = "#f0f0f0", i = test_formula) # pass it to the bg function
}

# Made a new variable for your list
test <- c("setosa", "versicolor")

# this does now -----------------
ft(df, "test")

Hope that helps

1 Like

Great. Thanks for that @jonesey441

I haven't seen that behaviour for passing variables to functions before.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.