call RMD file from python

Hello,

Is there any way to execute an RMD file from within a python script?

Both the RMD file and python live in an S3 bucket.

Thanks!

1 Like

I think the thing to do is take this in two steps. The first, is building an RMD from an R script. That would look something like this:

Sys.setenv(RSTUDIO_PANDOC = "/Applications/RStudio.app/Contents/MacOS/pandoc")
rmarkdown::render("my_doc.Rmd",
                  output_file = "docs/index.html")

Notice that I set the RSTUDIO_PANDOC environment variable. In my system I've found that it can't find the right version of PANDOC unless I do that.

The next step is to run the above code in Python. Probably the easiest way is to use rpy2 library for Python and do something like the following (untested):

import rpy2.robjects as robjects 

rcode = '''
   Sys.setenv(RSTUDIO_PANDOC = "/Applications/RStudio.app/Contents/MacOS/pandoc")
   rmarkdown::render("my_doc.Rmd",
                     output_file = "docs/index.html")
'''
robjects.r(rcode)

Or it might be a little easier to read if you just create an R script that has the build code then in Python do this:

import rpy2.robjects as robjects

robjects.r.source("my_build_script.R")

2 Likes

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