【发布时间】:2021-11-20 12:27:22
【问题描述】:
我使用 kableExtra 生成多个表格,我想使用一个函数而不是重复所有代码。但由于我对 R 的了解有限,我无法做到。
下面是一个简化的示例(如此简单,它没有说明我为什么要将所有代码折叠成一个函数)。第一个代码,没有任何附加的便利功能。
library(kableExtra)
library(glue)
library(tidyverse)
data <- mtcars[1:10, ] |> select(mpg, cyl, am, carb)
# KableExtra, without added convenience function
kbl(data, booktabs = T, linesep = "", digits = 2,
caption = "Ordinary kbl()") |>
add_header_above(c(" ", "Engine" = 2 , "Other" = 2))
)
尝试做同样的事情,现在使用一个函数,不同的调用可以使用不同的参数作为标题和添加的标题。标题部分工作正常,这是我正在努力添加的标题。
# Call kableExtra with a function
print_kable <- function(df, caption, header) {
kbl(data, booktabs = T, linesep = "", digits = 2,
# Caption works fine
caption = caption) |>
# I'm unable to develop code that uses a string argument here
add_header_above(c(header)) # 1 col instead of 5
# add_header_above(c({header})) # Same here
# add_header_above(c({{header}})) # and here
# add_header_above(c("{header}")) # and here
# add_header_above(c("{{header}}")) # and here
# add_header_above(c(glue({header}))) # and here
# add_header_above(c(paste(header))) # and here
}
Kable 应该使用下面的代码打印
print_kable(mtcars, caption = "kbl() called with a function",
header = ' " ", "Engine" = 2 , "Other" = 2 ')
这是一个相关的问题: How to evaluate a glue expression in a nested function?
【问题讨论】:
标签: r paste kableextra