Run R markdown (.Rmd) from inside other R script to produce HTML - r

As the example, if you create a new R markdown file and save it as 'test'. Can one then run or deploy this test.Rmd file from within a normal R script. The purpose being to generate the output in HTML, without having to open the .Rmd file.
I'm hoping to create one master file to do this for many markdown files in one go; which would save considerable time as you then don't have to open many markdown files and wait for each one to complete.

You are looking for rmarkdown::render().
Contents of "test.Rmd"
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
Contents of script.R
# provided test.Rmd is in the working directory
rmarkdown::render("test.Rmd")
A Way to Render Multiple Rmd
cwd_rmd_files <- list.files(pattern = ".Rmd$")
lapply(cwd_rmd_files, rmarkdown::render)

Thanks the-mad-statter, your answer was very helpful. The issue I faced, required me to prepare markdown dynamically. By adapting your code, that's easily possible:
Contents of "test_dyn.rmd"
---
title: "Untitled"
output: html_document
---
The chunk below adds formatted text, based on your inputs.
```{r text, echo=FALSE, results="asis"}
cat(text)
```
The chunk below uses your input in as code.
```{r results}
y
```
Contents of "script_dyn.r"
in_text <- c("**Test 1**", "*Test 2*")
in_y <- 1:2
lapply(1:2, function(x) {
text <- in_text[[x]]
y <- in_y[[x]]
rmarkdown::render(input = "test_dyn.rmd", output_file = paste0("test", x))
})
Like this you can create files with different text and different variables values in your code.

Related

Erro R "Error: '\U' used without hex digits in character string starting ""C:\U"

When starting RStudio, this error appears. I can run several commands, but I can't compile anything in Rmarkdown. Does anyone know how I can fix it?
The error does not appear when typing a path to read from the file. It even appears when I try to compile an empty file in RMarkdown.
The error even appears with the default example script in RMarkdown.
---
title: "Untitled"
author: "Autor"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.

R Markdown will not knit at all

My Rmarkdowns will no longer knit, every file give the same error.
Under the Render window, it says:
Error in library(emo) : there is no package called ‘emo’
Execution halted
However, I have never used a package called emo and that package is certainly not in this empty .Rmd file
I've tried updating R and RStudio, I'm just quite lost. Any guidance would help!
Here is my code, I haven't changed a single thing after opening the new .Rmd. has
---
title: "knitting_test"
author: "XXXXX"
date: "1/20/2022"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```

Can't generate plotly interactive plots in Rmarkdown report

I have an Rmarkdown document with a plot made with plotly and would like to generate an html file. It works when I click on Knit to HTML in Rstudio, but not when I run the following on the command line:
Rscript -e "require(knitr)" -e "require(markdown)" -e "knit('Untitled.Rmd', out='report.md')" -e "markdownToHTML('report.md', 'report.html')"
After this, I have a report.html file which contains the plot generated with plotly, but it is not interactive.
Does anyone know how to make it interactive with the command line?
Thanks
This is the code, btw:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure_ggplot, echo=FALSE}
library(ggplot2)
library(plotly)
ggplot(pressure,aes(temperature,pressure))+geom_point(size=10,color='red')
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
```{r pressure_plotly, echo=FALSE}
g<-ggplot(pressure,aes(temperature,pressure))+geom_point(size=10,color='red')
ggplotly(g)
```
```{r}
sessionInfo()
```
Try:
Rscript -e "library(knitr); library(rmarkdown); rmarkdown::render('untitled.Rmd', output_file='report.html')"
Reasoning: knit seems to default to markdown output, and doesn't retain HTMLwidgets in the rendered markdown. Thus, when converting, you end up with missing files (you can see these errors if you remove echo=FALSE from the code block openings.
rmarkdown::render([...]) renders cleanly to HTML, avoiding the issues mentioned above. If you wish to specify the output format, you can do so using the output_format argument.

Remove Markdown Default Code

In RStudio, whenever I make a new Markdown it always has default code. How do I remove it?
Here's the code that shows up.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Every time, when creating a Rmd file, Rstudio will open a Rmd template:
https://github.com/rstudio/rstudio/blob/822e558c7a274de464f992f69e3acee2fde5ab04/src/cpp/session/modules/SessionRMarkdown.R
# given a path to a folder on disk, return information about the R Markdown
# template in that folder.
.rs.addFunction("getTemplateDetails", function(path) {
# check for required files
templateYaml <- file.path(path, "template.yaml")
skeletonPath <- file.path(path, "skeleton")
if (!file.exists(templateYaml))
return(NULL)
if (!file.exists(file.path(skeletonPath, "skeleton.Rmd")))
return(NULL)
# load template details from YAML
templateDetails <- yaml::yaml.load_file(templateYaml)
# enforce create_dir if there are multiple files in /skeleton/
if (length(list.files(skeletonPath)) > 1)
templateDetails$create_dir <- TRUE
templateDetails
})
Hence the simplest solution would be:
go to xxx\RStudio\resources\templates folder, where your
Rstudio installed
open r_markdown_v2.Rmd file, and delete
everthing
save it
Now, everytime, when you open a rmarkdown, you can have just the yaml part.

Proper R Markdown Code Organization

I have been reading about R Markdown (here, here, and here) and using it to create solid reports. I would like to try to use what little code I am running to do some ad hoc analyses and turn them into more scalable data reports.
My question is rather broad: Is there a proper way to organize your code around an R Markdown project? Say, have one script that generates all of the data structures?
For example: Let's say that I have the cars data set and I have brought in commercial data on the manufacturer. What if I wanted to attach the manufacturer to the current cars data set, and then produce a separate summary table for each company using a manipulated data set cars.by.name as well as plot a certain sample using cars.import?
EDIT: Right now I have two files open. One is an R Script file that has all of the data manipulation: subsetting and re-categorizing values. And the other is the R Markdown file where I am building out text to accompany the various tables and plots of interest. When I call an object from the R Script file--like:
```{r}
table(cars.by.name$make)
```
I get an error saying Error in summary(cars.by.name$make) : object 'cars.by.name' not found
EDIT 2: I found this older thread to be helpful. Link
---
title: "Untitled"
author: "Jeb"
date: "August 4, 2015"
output: html_document
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
table(cars.by.name$make)
```
```{r}
summary(cars)
summary(cars.by.name)
```
```{r}
table(cars.by.name)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
plot(cars.import)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
There is a solution for this sort of problem, explained here.
Basically, if you have an .R file containing your code, there is no need to repeat the code in the .Rmd file, but you can include the code from .R file. For this to work, the chunks of code should be named in the .R file, and then can be included by name in the .Rmd file.
test.R:
## ---- chunk-1 ----
table(cars.by.name$make)
test.Rmd
Just once on top of the .Rmd file:
```{r echo=FALSE, cache= F}
knitr::read_chunk('test.R')
```
For every chunk you're including (replace chunk-1 with the label of that specific chunk in your .R file):
```{r chunk-1}
```
Note that it should be left empty (as is) and in run-time your code from .R will be brought over here and run.
Often times, I have many reports that need to run the same code with slightly different parameters. Calling all my "stats" functions separately, generating the results and then just referencing is what I typically do. The way to do this is as follows:
---
title: "Untitled"
author: "Author"
date: "August 4, 2015"
output: html_document
---
```{r, echo=FALSE, message=FALSE}
directoryPath <- "rawPath" ##Something like /Users/userid/RDataFile
fullPath <- file.path(directoryPath,"myROutputFile.RData")
load(fullPath)
```
Some Text, headers whatever
```{r}
summary(myStructure$value1) #Where myStructure was saved to the .RData file
```
You can save an RData file by using the save.image() command.
Hope that helps!

Resources