R read_yaml() reads a vector as parameter - r

I would like to read a .yaml file to get yaml parameters for a Rmarkdown report.
Original I have a yaml header to define a vector.
---
params:
ids: !r c(2455, 2490)
---
and it works, where params$ids is a vector.
However, if I put ids: !r c(2455, 2490) into a report_params.yaml file, and read that yaml file by
report_params <- yaml::read_yaml("report_params.yaml")
now report_params$ids is a string 'c(2455, 2490)'.
so what did I miss, and how should I fix this?

The YAML default handler uses !expr rather than !r.
report_params.yaml:
---
params:
ids: !expr c(2455, 2490)
---
yaml::read_yaml("report_params.yaml")
#> $params
#> $params$ids
#> [1] 2455 2490

Related

How do I dynamically adjust for text based on values of multipole columns and set as parameters in R markdown output pdf

Note the YAML. I have the title and author refer to set parameters
---
title: "`r params$ID_NUM`"
classoption: landscape
author: "`r params$first` `r params$last`"
date: "8/11/2021"
output:
pdf_document:
latex_engine: xelatex
html_document: default
params:
ID_NUM: 1
first: MICHAEL
last: DOUGLAS
---
The script below is able to output the pdf and provide me with the id number as a title. Where it does not work is it's not able to provide me the "author" portion with the corresponding name with id value. Do I do a nested for loop?
for (i in unique(df$id)) {
rmarkdown::render("Document.Rmd",
params = list(id_NUM = i),
output_file=paste0(i, ".pdf"))
}
if the dataset looks like this
id first last
1 Michael Douglas
2 Sean Penn
3 Kevin Bacon
I would like the first pdf to show
ID1
Michael Douglas
the second to show
ID2
Sean Penn
and last.
ID3
Kevin Bacon
I can get the ID portion but I can't get the names.
Update::
purrr::walk(df,function(x){
i<-df$id
p<-df$first
z<-df$last
rmarkdown::render(
"Document.Rmd",
output_file=paste0(i, ".pdf"),
params = list(id=i,first=p,last=z)
)
})
Tried with this script but did not work as well.
I believe that the following will work.
for (i in unique(df$id)) {
first <- df$first[df$id == i]
last <- df$last[df$id == i]
rmarkdown::render("Document.Rmd",
params = list(id_NUM = i, first = first, last = last),
output_file=paste0(i, ".pdf"))
}
The params values for first and last do not exist. By creating them, you should be able to get their values.

reticulate python engine - Use r as a name for Python object shared between multiple chunks

I am writing an R Markdown document using the Python engine of {reticulate}. I am quite happy with how it works.
The only thing is, I cannot use r as a Python object name that I'm going to use in multiple chunks.
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
r = 10
print(r) ##> 10
```
```{python}
print(r) ##> <__main__.R object at 0x119ad37d0>
```
I understand r is a good name when we use R objects from within a Python chunk. Since I know I am not going to do that in my project, I would like to use r as a name for my Python object.
Is there any way to change the name, r, for the R object created by reticulate? Or, to tell reticulate not to create r object?
I am aware of the two straightforward workarounds
Don't use r for Python objects.
Write everything in one big chunk and not share r between Python chunks.
but I'd like to have more freedom.
The object name r is special since it is used to communicate between R and python. The same holds for py in R:
---
title: "Untitled"
output: html_document
---
## Object name `r`
```{python}
foo = 10
print(foo) ##> 10
```
```{r}
library(reticulate)
py$foo ##> [1] 10
```
```{r}
foo <- 10
```
```{python}
print(foo) ##> 10
print(r.foo) ##> 10.0
```
Avoiding the use of r as an opject name is therefore the only good possibility I can see.
Still working on the details but I think setting source and output knit hooks may help. My dirty first try looks like this:
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
knitr::knit_hooks$set(
source = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
sprintf('<div class="%s"><pre class="knitr %s">%s</pre></div>\n', "source", tolower(options$engine), x)
},
output = function(x, options) {
if (!is.null(options$rsub)) x = gsub(options$rsub, 'r', x, fixed = TRUE)
paste0('<pre><code>', x, '</code></pre>\n')
}
)
```
```{python, rsub='rrr'}
rrr = 10
print(rrr)
```
```{python, rsub='rrr'}
print(rrr)
```

Error: Invalid YAML front matter (ends with ':')

The loop in the params not work, and i receive this message:
Error: Invalid YAML front matter (ends with ':')
The YAML is:
---
title: "Growth"
date: "16 de julho de 2019"
output:
html_document:
toc: true
toc_depth: 5
params:
data:
default
---
I see the default thing in other post, but he not work too.
The code is below:
data <- params$data
company <- c("usim5_test.pkl", "vale_test.pkl", "csn_test.pkl", "GGBR4_test.pkl")
for (i in company) {
rmarkdown::render(
input = "C:\\Users\\Rafael\\Documents\\ibov\\gurufocus\\macro\\growth_ibov1.Rmd",
output_file = paste0("Growth_",str_sub(i, 1,5),".html"),
params = list(
data = i
)
)
}
I expect render the reports for all the files
Kinda late (three years later), but i wanted to do the something and had the same problem.
I don't know if there is now easier ways to do this since I'm not a pro on R, still, it works if you first declare data = NULL in the YAML.

extract R code from template using knit_expand()

I have produced a dynamic document using knitr. The document makes
extensive use of the package's knit_expand() function for
templates. This is illustrated by the MWE (based on Yihui Xie's own
example for the function).
Main document knit-expand-MWE.Rnw
\documentclass{article}
\title{How to extract code when using\\
knit\_expand() for templates?}%
\author{Knitr User}
\begin{document}
\maketitle
\tableofcontents
\newpage
\section{Write one row of data}
Only the first two sections are evaluated.
<<run-all, include=FALSE>>=
library(knitr)
src = NULL
for (i in 1:3) src = c(src, knit_expand('template.Rnw'))
#
\Sexpr{paste(knit(text = src), collapse = '\n')}
\end{document}
Template template.Rnw called by main document
\subsection{Now i is {{i}}}
This chunk is {{if (i > 2) 'not '}}evaluated.
<<row-{{i}}, eval={{i <= 2}}>>=
# row number {{i}}
iris[{{i}}, ]
#
I now need to extract the corresponding R code. Running purl("knit-expand-MWE.Rnw") outputs knit-expand-MWE.R, which includes the code in the chunk with a reference to the template:
## ----run-all, include=FALSE----------------------------------------------
library(knitr)
src = NULL
for (i in 1:3) src = c(src, knit_expand('template.Rnw'))
What I would like instead is the corresponding "expanded" code (for the benefit of colleagues who do not use knitr), for example:
## ----row-1, eval=TRUE----------------------------------------------
## row number 1
iris[1, ]
## ----row-2, eval=TRUE----------------------------------------------
## row number 2
iris[2, ]
## ----row-3, eval=FALSE----------------------------------------------
## row number 3
iris[3, ]
How can I achieve this?
You can run purl() on src, e. g.
purl(text = src, output = 'knit-expand.R')

How to format Gmisc::htmlTable

Below is an rmarkdown document that can be pasted into rstudio.
My problem is that output from htmlTable is prepended/appended with cruft from the htmlTable attributes.
---
title: "SO_question"
author: "AC"
date: "Wednesday, May 28, 2014"
output:
html_document:
theme: readable
---
My heading
============
This is a few tables. Notice that `htmlTable` prints `[1]"` before each table and `" attr(,“class”) [1] “htmlTable” “character” [1] “` after each table. How can I avoid this?
``` {r html_table, results='asis', echo=FALSE, message=FALSE}
library("htmlTable")
library("reshape2")
#Chick weight example
names(ChickWeight) <- tolower(names(ChickWeight))
chick_m <- melt(ChickWeight, id=2:4, na.rm=TRUE)
for (i in unique(chick_m$diet)) {
diet <- subset(chick_m, diet==i)
table_to_print <- dcast(chick_m, time ~ variable, mean)
print(htmlTable(table_to_print, rgroup=c(""), n.rgroup=nrow(table_to_print)))
}
```
Bonus question: How to format the last row in each table as bold text (suited for a 'total' row)?
Rather than using print on your htmTable, use cat to properly render it.
for (i in unique(chick_m$diet)) {
diet <- subset(chick_m, diet==i)
table_to_print <- dcast(chick_m, time ~ variable, mean)
cat(htmlTable(table_to_print, rgroup=c(""), n.rgroup=nrow(table_to_print)))
}
There is a print.htmlTable function that is called when a print is performed on an object from the htmlTable function. It should automatically call the cat, not sure if this was true May '14 but it works today.
In the 1.1 version of the htmlTable-package (the function was separated from the Gmisc-package) there is a total option:
for (i in unique(chick_m$diet)) {
diet <- subset(chick_m, diet==i)
table_to_print <- dcast(chick_m, time ~ variable, mean)
print(htmlTable(table_to_print, total=TRUE))
}
Note: You do not need to specify the rgroup element if you are not using it.
#author

Resources