在函数中使用flextable :: display()

时间:2019-02-27 00:19:15

标签: r flextable

我正在尝试在一个函数内使用flextable::display()函数,并使用display内该函数的参数。下面是我的功能:

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')

我希望在a列中出现setosa的任何地方都获得上标Species,但是它给出以下错误,指示显示函数看不到参数传递给函数:

  

eval(as.call(f [[2]]),envir = data)中的错误:找不到对象'pattern'

有人知道如何从函数中获取参数以供内部display()函数识别吗?

1 个答案:

答案 0 :(得分:2)

函数display很难使用-这就是我编写flextable::compose的原因。它可以依靠整洁的eval语法。以下2个示例可以为您提供帮助:

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