I created an RMarkdown file file.Rmd with parameters.
I know how to access parameters within a r chunk but not from a bash chunk
If there is absolutely no way to do so, I will write the parameters in a file through r chunk and then read it from bash chunk...
---
output: html_document
params:
myParam1:
label: "Choose 1st parameter"
value: 20
input: slider
min: 0
max: 100
myParam2:
label: "Choose 2nd parameter"
value: "Hello"
input: text
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, echo=FALSE}
print(paste("1st parameter :",params$myParam1))
print(paste("2nd parameter :",params$myParam2))
```
```{bash}
# Don't know how to get parameters here
echo $params
```
Thanks
I've seen a few options
Use Sys.setenv to export variables from R to bash, so add this line to an R chunk.
Sys.setenv(params = params$myParam1)
Use the runr package
To apply the export-to-envirnoment idea from the accepted answer to all params, just add the following do.call loop to an R chunk before the bash chunk:
```{r, echo=FALSE, message=FALSE}
for (key in names(params)) {
do.call('Sys.setenv', params[key])
}
```
Thanks Chris S, this works fine.
I share the workaround I used (create tmp file) in case someone would be interested :
---
output: html_document
params:
myParam1:
label: "Choose 1st parameter"
value: 20
input: slider
min: 0
max: 100
myParam2:
label: "Choose 2nd parameter"
value: "Hello"
input: text
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Chris solution :
```{r, echo=FALSE}
Sys.setenv(param1=params$myParam1)
Sys.setenv(param2=params$myParam2)
```
```{bash, echo=FALSE}
echo $param1
echo $param2
```
My workaround :
```{r}
param1 <- paste0("param1=\"",params$myParam1,"\"")
param2 <- paste0("param2=\"",params$myParam2,"\"")
# Write parameters in temporary file
fileConn <- file("~/params.tmp")
writeLines(c(param1,param2), fileConn)
close(fileConn)
```
```{bash, echo=FALSE}
. ~/params.tmp
rm ~/params.tmp
echo $param1
echo $param2
```
Related
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)
```
I am trying to do the following on R Markdown. Basically, I would like the user to be able to select between two values of a parameter called "Machine" and based on the value selected run some chunks and not others. I know that the "eval" option might be useful here but I have no clue on how to use it in order to reach my goal.
My code for the moment is this (in R Markdown):
---
title: "SUM and SAM"
output: html_document
params:
machine:
label: "Machine"
value: SUM
input: select
choices: [SUM, SAM]
printcode:
label: "Display Code:"
value: TRUE
date: !r Sys.Date()
data:
label: "Input dataset:"
value: None
input: file
years_of_study:
input: slider
min: 2018
max: 2020
step: 1
round: 1
sep: ''
value: [2018, 2019]
---
```{r setup, include=FALSE}
############# IMPORTANT ###################################
#Remember to Knit with Parameters here using the "Knit button"--> "Knit with Parameters".
####################################################
#If you only want the parameters to be shown, run the following.
#knit_with_parameters('~/Desktop/Papers/git_hub/sum_sam.Rmd')
#This must be left uncommented if we want to show the content of the Markdown file once "Knit with Parameters" is pressed.
knitr::opts_chunk$set(echo = TRUE)
Say now I would like a chunk that will execute only if machine = SAM. How can I do that?
Was thinking about something like:
{r pressure, echo=FALSE, eval=params$machine}
plot(pressure)
but does not work
Thank you,
Federico
Let there be a file called foo.Rmd with this content:
---
title: "SUM and SAM"
output: html_document
params:
machine:
input: select
choices: [SUM, SAM]
value: SUM
---
```{r, eval = params$machine == "SAM", echo=FALSE}
print("SAM was chosen")
```
```{r, eval = params$machine == "SUM", echo=FALSE}
print("SUM was chosen")
```
Then you can do:
rmarkdown::render("foo.Rmd", params = list(machine = "SAM"))
Alternativeley, there is the option knit with parameters in RStudio:
Resulting in foo.html:
I use this rmd:
---
title: "Some Title"
author: "Some Author"
date: "`r format(Sys.time(), '%d-%m-%Y')`"
---
## A function that generates sections
```{r setup, include = FALSE}
library(pander)
create_section <- function() {
# Inserts "## Title (auto)"
pander::pandoc.header('Title (auto)', level = 2)
# Section contents
# e.g. a random plot
plot(sample(1000, 10))
# a list, formatted as Markdown
# adding also empty lines, to be sure that this is valid Markdown
pander::pandoc.p('')
pander::pandoc.list(letters[1:3])
pander::pandoc.p('')
}
```
## Generate sections
```{r, results='asis', echo=FALSE}
n_sections <- 3
for (i in seq(n_sections)) {
create_section()
}
```
and then:
library(knitr);
library(rmarkdown);
setwd("C:/bla")
knit('test_md.Rmd')
rmarkdown::pandoc_convert("test_md.md", to = "pdf", output = "test_pdf.pdf")
This kind of works but the plots are all rendered after the sections:
Each section should contain the plot. Any ideas? Thanks!
PS:
Wrapping:
plot(sample(1000, 10))
in print:
print(plot(sample(1000, 10)))
forces output to be produced. Unfortunately, NULL is also printed underneath the plot.
Could you just add pdf_document in the YAML and then generate the PDF by knitting?
---
title: "Some Title"
author: "Some Author"
date: "`r format(Sys.time(), '%d-%m-%Y')`"
output: pdf_document
---
I was able to get the same result you described when running the rmarkdown::pandoc_convert() on the .md file, all the plots at the end of the .PDF file.
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:
Im new to Rmarkdown and I would like to create dynamic reports where every report section is generated from a template (child) document. Each section will then start with a newpage in the rendered pdf.
My approach is currently based on this post which shows how to generate dynamically text in the child (which works), however I am not able to transfer the contents of the loop into a R-Codeblock, probably because the params are not well defined in the way that I tried to do it.
This is how my parent document looks like:
---
title: "Dynamic RMarkdown"
output: pdf_document
---
```{r setup, include=FALSE}
library("knitr")
options(knitr.duplicate.label = "allow")
```
# Automate Chunks of Analysis in R Markdown
Blahblah Blabla
\newpage
```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
out = c(out, knit_expand('template.Rmd'))
params <- list(species = i)
}
```
`r paste(knit(text = out), collapse = '\n')`
and this is how the child looks like
---
title: "template"
output: html_document
params:
species: NA
---
# This is the reporting section of Species {{i}}
This is a plot of Sepal length and width based on species {{i}}.
```{r plot2}
paste(params$species)
# plot doesnt work work
# plot(iris$Sepal.Length[iris$Species=={{i}}],
# iris$Sepal.Width[iris$Species=={{i}}]
# )
```
\newpage
To my understanding the parameter that is actually passed is the last species from the dataset generated in the loop but I'm not sure why the plot would't work then. Can anybody help me out on how to fix this issue?
Ok. No need to go through params. The solution was simply to put i between brackets AND parenthesis in the child-document.
Parent:
---
title: "Dynamic RMarkdown"
output: pdf_document
---
```{r setup, include=FALSE}
library("knitr")
options(knitr.duplicate.label = "allow")
```
# Automate Chunks of Analysis in R Markdown
Blahblah Blahblah Main text before individual sections
\newpage
```{r run-numeric-md, include=FALSE}
out = NULL
for (i in as.character(unique(iris$Species))) {
out = c(out, knit_expand('template.Rmd'))
}
```
`r paste(knit(text = out), collapse = '\n')`
Child
---
title: "template"
output: html_document
---
# This is the reporting page of Species {{i}}
This is a plot of Sepal length and width based on species {{i}}.
```{r plot2}
paste("This will be a plot of Sepal Length and Witdh from", '{{i}}')
plot(iris$Sepal.Length[iris$Species=='{{i}}'],
iris$Sepal.Width[iris$Species=='{{i}}']
)
```
\newpage
Original solution found here.