sjPlot::tab_model file argument not working with Knit in RStudio

tab_model has a file argument to direct html output to a file:
tab_model(fit, file = "xxx.html")
But this does not produce the desired output file when run in an Rmd script using the "Knit" button in RStudio.
If I run the same code either by pasting it into the console, or by Run Current Chunk in RStudio, it works and creates the output file.
RStudio 1.4.1717, sjPlot 2.8.9
Reproducible example:

---
title: "Reproducible example of tab_model file issue"
author: "Me"
date: "2/19/2022"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Run this chunk in console, does not produce correct output if knit.

```{r tabmodel}
library(sjPlot)

fit <- lm(mpg ~ cyl, data=mtcars)
tab_model(fit, file = "tabmodelOut.html")
# should produce html output in this named file.
#Does not do so if Rmd file is "knit" in RStudio
# Does correctly produce this output file if Run Current Chunk in RStudio
```

I believe this is expected from how sjPlot is working.

  • When you click the Knit button, code will be exectute in the knit context. This means than a special printing method will be used. knitr::knit_print. sjPlot defines a special method sjPlot:::knit_print.sjTable() to print its table. If you look at the source, this function won't write to file, but will output directly in the file as usual during knitting.

  • When you run outside of knit, then print() will be used. And this is sjPlot:::print.sjTable() that will write to file if you look at the source code.

So I believe this is current expected behavior. You can open a feature request in sjPlot to do both in case somehow when knitting.

If you really want only the writting to file and not table included in the knitted output, then you could just hack and print the value to file explicitly.

```{r tabmodel}
library(sjPlot)

fit <- lm(mpg ~ cyl, data=mtcars)
# if file is defined, sjPlot:::print.sjTable will write to file, always.
print(tab_model(fit, file = "tabmodelOut.html"))
```

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.