Why do Rmd change global variables (default)? - r

I never expected the following bahavior:
Save the following Rmd in /folder as testi.Rmd
---
title: "testi"
author: ""
date: "29 November 2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
i <- 15
```
Then run the following script
i <- 0
print(i)
rmarkdown::render("folder/testi.Rmd", encoding = "UTF-8", quiet = TRUE)
print(i)
In the end, i is set to 15 because of the chunk in the Rmd? It took quite some time to figure that out. Is that intended? What is the use case here which allows "rendering" variables to change? I could not find anything in the web or in ?rmarkdown::render

What you're looking for is the envir argument. Run the following script to see
i <- 0
print(i)
rmarkdown::render("folder/testi.Rmd", encoding = "UTF-8", quiet = TRUE, envir=new.env())
print(i)

Related

knitr::include_graphics: safe way to read from the project directory?

I am trying to make a RMarkdown report using bookdown::html_document2 to create numbered Fig. 1, Fig. 2, ... across the whole document. Here, I am using both the R-generated and the external figures. I have found that using include_graphics() will help to generate a proper Fig. X numbers, also including in numbering the external figures.
To get the script to work, I am declaring the root.dir = rprojroot::find_rstudio_root_file('C:/myRproject')) while my external figures are located within C:/myRproject/inImg. But in this case, R cannot find my external images anymore? Why is this and how can I properly claim the paths for my R Markdown input, and for external figures? Thank you!
Example:
---
title: "My awesome title"
author: "me"
date: "`r Sys.Date()`"
output:
bookdown::html_document2:
toc: true
toc_depth: 3
knit: (function(input, ...) {
rmarkdown::render(
input,
output_dir = "../outReports",
output_file = file.path("../outReports", glue::glue('test_{Sys.Date()}'
)))
})
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, tidy = TRUE, tidy.opts = list(comment = FALSE), message = F, warning = F)
knitr::opts_chunk$set(fig.width=6, fig.height=3)
library(knitr)
library(png)
```
```{css, echo=FALSE}
p.caption {
font-size: 0.8em;
}
```
```{r setup-root}
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file('C:/myRproject'))
```
```{r read-libs, eval = TRUE, echo=FALSE, include = FALSE, warning = FALSE, error = FALSE }
# rm(list=ls())
getwd()
#### Source paths and functions -----------------------------------------------
source('myPaths.R') # already this one I can't find within the directory?
# Read pictures as part of teh R chunks
library(knitr)
library(png)
# Read Input data -------------------------------------------------------------------
#getwd()
load(file = "outData/dat1.Rdata")
```
## Including Plots
You can also embed plots, for example:
```{r, out.width = "50%", fig.cap = 'Add fig from internet'}
include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/MC_Drei-Finger-Faultier.jpg/330px-MC_Drei-Finger-Faultier.jpg")
```
```{r add-extern-plot2, fig.cap = 'my numbered caption'}
# All defaults
img1_path <- "C:/myRproject/inImg/my_extern_fig.png"
img1 <- readPNG(img1_path, native = TRUE, info = TRUE)
attr(img1, "info")
include_graphics(img1_path)
```

Getting "Error: attempt to use zero-length variable name" in Rmd file in RStudio

In RStudio, I am getting 'Error: attempt to use zero-length variable name' in the following R code block:
```{r setup, include=FALSE}
# knitr::opts_chunk$set(echo = TRUE)
pb52_in <- read.csv("../data/pb52.csv", T)
pb52 <- pb52_in
```
This is the output:
Show in New Window
Error: attempt to use zero-length variable name
> # knitr::opts_chunk$set(echo = TRUE)
> pb52_in <- read.csv("../data/pb52.csv", T)
> pb52 <- pb52_in
>
Error: attempt to use zero-length variable name
I haven't modified the file yet, and I am only running this code block. This is my first time using Rstudio and working with R, so I am a little lost. I checked for other similar questions, and they said to check for the correct formatting of ```; I tried that but without success.
I solved the issue. Hopefully, it will help others:
After the code block:
```{r setup, include=FALSE}
# knitr::opts_chunk$set(echo = TRUE)
pb52_in <- read.csv("../data/pb52.csv", T)
pb52 <- pb52_in
```
I have this:
---
title: "Title"
author: "Author"
date: "XX/XX/XXXX"
output: html_document
---
I added an empty line between the last "```" and "---", and that solved the issue

Create code snippets by a loop in rmardown

Similar to how to create a loop that includes both a code chunk and text with knitr in R i try to get text and a Code snippet created by a Loop.
Something along this:
---
title: Sample
output: html_document
params:
test_data: list("x <- 2", "x <- 4")
---
for(nr in 1:3){
cat(paste0("## Heading ", nr))
```{r, results='asis', eval = FALSE, echo = TRUE}
params$test_data[[nr]]
```
}
Expected Output would be:
What i tried:
I tried to follow: https://stackoverflow.com/a/36381976/8538074. But printing "```" did not work for me.
You can make use of knitr hooks. Take the following MRE:
---
title: "Untitled"
output: html_document
params:
test_data: c("x <- 2", "x <- 4")
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, results = 'asis', echo = F}
hook <- knitr::hooks_html()$source
opts <- knitr::opts_chunk$get()
chunks <- eval(parse(text = params$test_data))
for(nr in seq_along(chunks)){
cat(paste0("## Heading ", nr, "\n"))
cat(hook(chunks[nr], options = opts))
}
```
We get the default source hook and also the default chunk options. Then we get the test data, which is supplied as a string. Therefore we parse and evaluate that string.
In the loop we simply call the source hook on each element of the test data. Here is the result:

R markdown YAML issue

I am using R Markdown render to automate sales reporting and I am hit with the following error message:
Error: Invalid YAML front matter (ends with ':').
R Studio, function worked previously. I have tried most quick fixes I've seen online but nothing has worked.
Additionally, if you have any advice for importing company logos, I would love to hear it. When knitted locally, it appears, but once it is sent out, it disappears. I'm sure this is due to the local file path, so any advice for calling it in a non-local manner?
---
output: html_document
params:
---
![](/Users/bingbong284/Desktop/markdown/CopyOf Header.jpg)
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, comment = NA)
library(dplyr)
library(tidyverse)
library(knitr)
library(kableExtra)
library(yaml)
library(rmarkdown)
```
```{r echo=FALSE, message=FALSE, warning=FALSE, paged.print=FALSE, comment = NA}
today <- Sys.Date()
```
`r format(today, format="%B %d, %Y")`
To Whom It May Concern,
Below is your sales report for fictitious name.
```{r include=FALSE}
aug_rent <- read_csv("Aug R Rent.csv")
colnames(aug_rent)[colnames(aug_rent)=="Vendor ID"] <- "Landlord"
organ_aug <- arrange(aug_rent, aug_rent$'Landlord')
vendors <- unique(organ_aug$`Landlord`)
```
```{r echo=FALSE}
render_my_report <- function(vendor) {
rmarkdown::render("Remote.Rmd",
output_format = "html_document",
output_file = paste0(vendor, "_sales_report_", Sys.Date(), ".html"),
params = list(Landlord = vendor),
output_options = list(self_contained = FALSE, lib_dir = "libs"))
}
purrr::walk(vendors, render_my_report)
```
```{r echo=FALSE, message=FALSE, warning=FALSE, comment=NA}
test_data <- filter(organ_aug, organ_aug$'Landlord' == params)
last_table <- knitr::kable(test_data, captio = "August 2019 Sales Report")
kable_styling(last_table, font_size = 14)
```
If you have any questions regarding this report, please email BingBong284#ficticiousname.com or reach out to BingBong284, BingBong284#ficticiousname.com.
Thank you,
BingBong284, Finance
Function previously generated 66 unique sales reports for 66 vendor ID's, but it is now hitting me with the error listed above.

How to use LaTeX Code in R Chunk in R-Markdown?

I am currently writing on a report with rmarkdown and therefore I want to create sections inside a r code chunk. I figured out that this is possible with the help of cat() and results="asis". My problem with this solution is, that my R code results and code isn't properly displayed as usual.
For example
---
title: "test"
output: pdf_document
---
```{r, results='asis'}
for (i in 1:10) {
cat("\\section{Part:", i, "}")
summary(X)
$\alpha = `r X[1,i]`$
}
```
pretty much does the trick, but here there are still two problems:
the R output for summary() is displayed very strange because I guess it`s interpreted as LaTeX code
I can't use LaTeX formulas in this enviroment, so if I want every section to end with a equation, which also might use a R variable, this is not possible
Does somebody know a solution for some of these problems, or is there even a workaround to create sections within a loop and to have R code, R output and LaTeX formulas in this section? Or maybe at least one of those things?
I am very thankful for every kind of advice
You can do what you are after inline without relying as much on code blocks.
As a minimal example.
---
title: "test"
output: pdf_document
---
```{r sect1_prep, include=FALSE}
i <- 1
```
\section{`r paste0("Part: ", i)`}
```{r sect1_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
```{r sect2_prep, include=FALSE}
i <- i + 1
```
\section{`r paste0("Part: ", i)`}
```{r sect2_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
Produces...
If you really want to have a section factory, you could consider pander.
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
empty <- lapply(1:10, function(x) {
pandoc.header(paste0("Part: ", x), level = 2)
pander(summary(mtcars[, x]))
pander(paste0("$\\alpha = ", mtcars[1, x], "$\n"))
})
```
which produces...
remove summary table format example
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
content <- lapply(1:10, function(x) {
head <- pandoc.header.return(paste0("Part: ", x), level = 2)
body1 <- pandoc.verbatim.return(attr(summary(mtcars[, x]), "names"))
body2 <- pandoc.verbatim.return(summary(mtcars[, x]))
eqn <- pander_return(paste0("$\\alpha = ", mtcars[1, x], "$"))
return(list(head = head, body1 = body1, body2 = body2, eqn = eqn))
})
writeLines(unlist(content), sep = "\n\n")
```

Resources