RMarkdown - chunk runs but not based on source

Hi everyone,

I'm relatively new to RMarkdown. I created a chunk that runs my R script that has a gt table. It runs fine and renders perfectly, but when I try to source it back to a script instead of embedding it into the RMarkdown file, all I get is the YAML title. Any ideas what's going on?

John

Hi @JohnN8797. Does the final line of the script return the gt table?

Hi @scottyd22 yes it does. If the whole script is embedded in the R Markdown file, it renders fine. It's only when I try to source to a script that it doesn't show up. There's also no errors that show up.

@JohnN8797 I believe that when you source() you need to use explicit print() calls on the objects you wish to show up. See the details section in this documention. Trying placing the object that you wish to print in a print() function call in the script that you are sourcing (if it isn't already in one).

Is it in the source code that I put the gt table call in a print function?

So at the end of the gt script I type out the name of the table to have it rendered. Instead of that, do I put it within the print function? E.g., print (nameofgttable). Or is it in the RMarkdown file?

Yes, so in your Rmarkdown down document you'll just have source("your_r_script") and in your sourced script you'll have
print(table_object) I assume near the end.

That just outputted a bunch of misc text :frowning:

Forgot to mention that I'm rendering it to an HTML page.

Try return() instead of print()

Nope, came back blank now.

Try this:

In your script that you will source, make sure to assign your gt table to an object name.

Then in your Rmarkdown, do print(your_gt_table_name).

I agree with this, but instead of print(), I found using return() in rmarkdown to work.

Sample script ("myscript.R")

library(gt)
out = gt(head(mtcars, 5))

Rmd file (only two ticks used to show code chunk below)

---
title: ''
output: html_document
---

``
{r, echo= FALSE, warning=FALSE, message=FALSE}
source('myscript.R')
return(out)
``

Output
image

2 Likes

That worked! Thank you!!

This topic was automatically closed 21 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.