I have a function which produces multiple tables, e.g. one a reactable, the other the simple printout of a dataframe.
When using the function in a quarto document and rendering it, the output of the reactable is omitted unless it comes last in the function.
Any idea what's going on? I assume it's related to the issue dealt with here, but I don't see how to overcome it.
Many thanks.
Below the code which should reproduce the issue in a qmd document.
---
title: "Untitled"
format: html
---
```{r}
#| echo: true
#| warning: false
library(tidyverse)
library(reactable)
```
Reactable first; not shown in output
```{r}
fn_cars <- function(my_data) {
my_data[1:5,] %>% reactable()
print(my_data[1:5,])
}
```
```{r}
fn_cars(my_data=mtcars)
```
Reactable last, shows in output.
```{r}
fn_cars <- function(my_data) {
print(my_data[1:5,])
my_data[1:5,] %>% reactable()
}
```
```{r}
fn_cars(my_data=mtcars)
```
The problem you are facing is not actually quarto
or reactable
specific. Its actually how R function works. By default, an R function returns the value of the last expression evaluated.
So in your example, the first function is printing the my_data
, since the print
was the last expression and returning the my_data
invisibly and so You are getting only the printed data, not the reactable. But the second function is printing the my_data
and returning the reactable
output and that's why you are getting both of them in the output in the second case.
With this fact in mind, either
fn_cars <- function(my_data) {
table <- my_data[1:5, ] %>% reactable()
print(my_data[1:5, ])
table
}
fn_cars(my_data=mtcars)
or
fn_cars <- function(my_data) {
print(my_data[1:5, ])
table <- my_data[1:5, ] %>% reactable()
table
}
fn_cars(my_data=mtcars)
will work as intended.