0

我希望我的函数打印漂亮的表格,无论是从基础 R 还是从 RStudio Notebook(.Rmd文件)调用。该函数应该确定从哪里调用它,并相应地调整表格。我希望该函数易于使用,并且不希望用户必须指定有关从何处调用该函数的任何信息。

我可以用 实现其中的一些huxtable,但用户仍然需要稍微修改代码。(我认为这与 . 类似kable。)

这是函数定义:

library(huxtable)

func = function() {
    table = hux(head(iris))
    # Color of table border: white on screen / base R, black in HTML
    color = if(isTRUE(all.equal(getOption('huxtable.print') , huxtable::print_screen))) "white" else "black"
    table = set_all_borders(table, brdr(color = color))
    print(table)
}

在基础 R 中,我可以调用该函数:

# Base R
func()

但是在 RStudio Notebook 中,我需要在调用函数时进行一些更改,即:

  • {r, results="asis"}
  • options("huxtable.print" = huxtable::print_html)

调用如下所示:


    ```{r, results="asis"}
    # RStudio
    options("huxtable.print" = huxtable::print_html)
    func()
    ```

有没有更好的解决方案,用户可以在基本 R 和 RStudio 中以相同的方式调用函数?

4

2 回答 2

2

也许是这样的?

library(huxtable)

func = function(table) {
    html_output = isTRUE(all.equal(getOption('huxtable.print') , 
                         huxtable::print_html) || 
                  guess_knitr_output_format() == "html"
    color = if(html_output) "black" else "white"
    table = set_all_borders(table, brdr(color = color))
    print(table)
}

于 2022-02-09T17:48:51.070 回答
0

感谢@dash2 给了我这个想法。这是我想要的功能:

library(huxtable)

func = function() {
    table = hux(head(iris))
    if (guess_knitr_output_format() == "") { # base R
        table = set_all_borders(table, brdr(color = "white"))
        print(table, colnames = FALSE)
    } else { # knitr / RStudio
        table = set_all_borders(table, brdr(color = "black"))
        huxtable:::knit_print.huxtable(table, colnames = FALSE)
    }
}

func()
于 2022-02-09T18:54:14.313 回答