【问题标题】:Pasting within a function used to print with kableExtra在用于打印的函数中粘贴 kableExtra
【发布时间】: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


    【解决方案1】:

    将函数c() 放在函数调用中而不是函数本身中可以正常工作。这是你要找的吗?

    print_kable <- function(df, caption, header) {
      kbl(data, booktabs = T, linesep = "", digits = 2,
          caption = caption) |>
        add_header_above(header)
    }
    
    print_kable(mtcars, caption = "kbl() called with a function", 
                header = c(" ", "Engine" = 2 , "Other" = 2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2014-07-23
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      相关资源
      最近更新 更多