0

I want my function to print nice-looking tables, whether it's called from base R or from an RStudio Notebook (.Rmd file). The function should figure out where it's being called from, and adjust the table accordingly. I want the function to be easy to use, and don't want the user to have to specify anything about where the function is being called from.

I can achieve some of this with huxtable, but the user still has to modify the code a little. (I think this would work similarly with kable.)

Here is the function definition:

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)
}

In base R, I can just call the function:

# Base R
func()

But in an RStudio Notebook, I need to make a couple of changes when calling the function, namely:

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

The call looks like this:


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

Is there a better solution where the user can call the function the same way in base R and RStudio?

Jessica
  • 113
  • 4

2 Answers2

2

Maybe something like this?

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
  • 2,024
  • 6
  • 15
  • That's a very useful find. It allows me to get rid of the `options` statement. However, I still need to do the `{r, results="asis"}` part. – Jessica Feb 09 '22 at 18:15
  • Rather than printing the table, why not return it? At the top level, it will be printed. – dash2 Feb 10 '22 at 09:38
0

Thanks to @dash2 for giving me the idea. Here is the function that does what I want:

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()
Jessica
  • 113
  • 4
  • 1
    See my other comment: I'd recommend returning the table, so that it can be autoprinted by the REPL or by knitr. The other thing you could do is set this as the method for `options(huxtable.print)`. – dash2 Feb 10 '22 at 09:40