使用flextable编程

时间:2019-01-31 06:59:43

标签: r flextable

我有一个函数可以生成具有以下结构的数据帧:

df <- data.frame(selected.variable = paste(letters[1:5], '_'),
             percentage = c(50, 20, 10, 10, 10))

来自更大的数据框。

也就是说,在我正在使用的数据框中,有一列带有所选变量的标签,第二列给出了出现该标签的情况的百分比。

我想使用包flextable https://github.com/davidgohel/flextable创建这些数据帧的表。我可以使用以下代码直接执行此操作:

percent_format <- function(x){
  sprintf("%.1f %%", x)
}

labels_format <- function(x) {
  x <- gsub(pattern = '_', replacement = '', x = x)
  return(x)
}

table <- regulartable(df) 
table <- set_header_labels(table, selected.variable = 'New name', percentage = 'Percentage')
table <- set_formatter(table, selected.variable = labels_format, 
                       percentage = percent_format)

我想编写一个函数,以编程方式更新所选变量的名称和格式-像这样:

make.flextable <- function(data, variable, variable.name) {

percent_format <- function(x){
      sprintf("%.1f %%", x)
    }

    labels_format <- function(x) {
      x <- gsub(pattern = '_', replacement = ' ', x = x)
      return(x)
    }

    table <- regulartable(data) 
    table <- set_header_labels(table, variable = variable.name, percentage = 'Percentage')
    table <- set_formatter(table, variable = labels_format, 
                           percentage = percent_format)

return(table)
} 

但是,我不知道如何将所选变量的名称(例如,上面示例中的“ selected.variable”)传递给flextable。我已尝试根据此问题使用map2函数:

In nested data frame, pass information from one list column to function applied in another

但无法使其正常工作。

1 个答案:

答案 0 :(得分:1)

由于几天来,github上有一个新版本(不久将在cran上提供),请尽可能进行更新,因为以下代码仅在新版本上进行了测试。我不确定这不是您想要的,但是至少该示例显示了一些可以重用的代码:

library(flextable)

labels_format <- function(x) {
  x <- gsub(pattern = '_', replacement = ' ', x = x)
  return(x)
}
percent_format <- function(x){
  sprintf("%.1f %%", x)
}


make.flextable <- function(data, percent_variables, label_variables, labels ) {

  table <- flextable(data) 

  table <- set_header_labels(table, values = labels)

  # a simple function to format number
  table <- colformat_num(table, col_keys = percent_variables, digits = 1, suffix = "%" )

  # how to do with labels_format, create a named list
  args <- rep(list(labels_format), length(label_variables))
  names(args) <- label_variables

  # older versions :
  # table <- do.call(set_formatter, append(args, list(x=table) ) )
  table <- set_formatter(table, values = args )

  table <- set_header_labels(table, values = labels)
  # older versions :
  # table <- do.call(set_header_labels, append(labels, list(x=table) ) )
  return(autofit(table))
} 

df <- data.frame(selected.variable = paste(letters[1:5], '_'),
                 percentage = c(50, 20, 10, 10, 10), stringsAsFactors = FALSE)
ft <- make.flextable(df, 
               percent_variables = 'percentage', 
               label_variables = "selected.variable", 
               labels = list(selected.variable = "new name", 
                             percentage = "Percentage"
                             ))

print(ft)

enter image description here