[英]Nice looking tables in both base R and RStudio notebooks
我希望我的 function 打印漂亮的表格,無論它是從 base R 還是從 RStudio 筆記本( .Rmd
文件)調用的。 function 應該弄清楚它是從哪里調用的,並相應地調整表格。 我希望 function 易於使用,並且不希望用戶必須指定有關從何處調用 function 的任何信息。
我可以使用huxtable
實現其中的一些功能,但用戶仍然需要稍微修改代碼。 (我認為這與kable
的工作方式類似。)
這是 function 的定義:
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 中,我可以調用 function:
# Base R
func()
但是在 RStudio Notebook 中,我需要在調用 function 時進行一些更改,即:
{r, results="asis"}
options("huxtable.print" = huxtable::print_html)
電話看起來像這樣:
```{r, results="asis"}
# RStudio
options("huxtable.print" = huxtable::print_html)
func()
```
有沒有更好的解決方案,用戶可以在 base R 和 RStudio 中以相同的方式調用 function?
也許是這樣的?
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)
}
感謝@dash2 給我這個主意。 這是執行我想要的操作的 function:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.