I am trying to use the flextable::display()
function from within a function, using the arguments from the function within display. Below is my function:
add_footnote <- function(df, col, pattern, symbol){
tmp <- df
pat <- paste0(pattern, " {{x}}")
tmp <- display(tmp,
col_key = col,
i = ~ col == pattern,
pattern = pat,
formatters = list(x ~ as.character(symbol)),
fprops = list(x = fp_text(vertical.align = 'superscript')) )
return(tmp)
}
# Call function
df <- regulartable(head(iris))
add_footnote(df, col = 'Species', pattern = 'setosa', symbol = 'a')
I'm hoping to get a superscript a
wherever setosa
appears in the Species
column, however it gives the following error indicating that the display function can't see the arguments being passed to the function:
Error in eval(as.call(f[[2]]), envir = data) : object 'pattern' not found
Does anyone know how to get the arguments from the function to be recognised by the internal display()
function?
The function display
is quite hard to use - that's why I wrote flextable::compose
. It can rely on tidy eval syntax. Below 2 examples that should help you:
library(flextable)
library(officer)
library(rlang)
add_footnote_with_rlang <- function(df, col, pattern, symbol){
form_ <- sprintf("~ %s == '%s'", col, pattern)
colname <- enquo(col)
flextable::compose(
x = df, j = col, i = as.formula(form_),
value = as_paragraph(
as_chunk(!!colname),
as_chunk(symbol, props = fp_text(vertical.align = 'superscript')))
)
}
add_footnote <- function(df, col, pattern, symbol){
form_ <- sprintf("~ %s == '%s'", col, pattern)
flextable::compose(
x = df, j = col, i = as.formula(form_),
value = as_paragraph(
as_chunk(symbol, props = fp_text(vertical.align = 'superscript')))
)
}
# Call function
df <- regulartable(head(iris))
# df <- add_footnote(df, col = 'Species', pattern = 'setosa', symbol = 'a')
df <- add_footnote_with_rlang(df, col = 'Species', pattern = 'setosa', symbol = 'a')
df