Looping on rmarkdown::render() do not print table in Word document - r

I am trying to include a table in a Word document but with no results. What I get in the resulting document is just a text list of the elements of the table including column names.
My code is organized in two scripts:
Script calling Markdown file KG-report.Rmd
rmarkdown::render("KG-report.Rmd", params = list(
pest.name = pest.name),
output_file = paste0("Report-", pest.name, ".docx")
Markdown script KG-report.Rmd
---
title: "Some title"
author: "me"
date: "`r Sys.Date()`"
output:
officedown::rdocx_document:
reference_docx: Simple_master_template_opinions.docx
tables:
style: Table
params:
pest.name: "Default pest"
---
```{r process-map, echo=FALSE, warning=FALSE, message=FALSE, fig.keep='all'}
# create and check directories
source("R_scripts\\PEST.PROFILE.check.pest.directories.r", local = knitr::knit_global())
# download distribution tables or load reviewed distribution table
source("R_scripts\\PEST.PROFILE.web.EPPO.distribution.table.r", local = knitr::knit_global())
knitr::kable(pest.kg.table)
etc...
After many tests and after following suggestions on word formatting (e.g. here) which did not solve the issue, it looks like the problem is related to looping on
rmarkdown::render()
If I do not use it the table is printed....
Is there any known issue about this or am I just using it in the wrong way?
Thank you
UPDATE - SOLUTION FOUND
In the end I was able to find a solution. It looked like the kable function was printing a html table in the word file which resulted in text with no table formatting. Adding the argument format = "pipe" solved the issue.

Related

How can I generate and knit personalized versions of an .Rmd report?

I have created a report PerfReport.Rmd that compares one person's performance to the performance of a large group. I have hundreds of individuals that should receive a personalized version of this report, comparing their own performance to the large group.
Obstacles I see are:
1. I need each filename to include the person's name.
2. Each file has calculations that are specific to the person.
Here's an example .Rmd
---
title: "Course Success"
output:
html_document: flexdashboard::flex_dashboard
pdf_document: default
---
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(dplyr)
library(plotly)
```
```{r comp, echo=FALSE, message=FALSE,warning=FALSE}
df<-data.frame(Person=c('a','a','a','a','a','b','b','b','b','b','c','c','c','c','c','d','d','d','d','d'),
Success=c(1,0,1,1,0,1,0,0,0,0,1,1,1,1,1,0,1,0,0,1),
Valid=c(1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1))
testperson<-'b'
comparison<-df%>%
transmute(Your_Rate=sum(Success[Person==testperson])/sum(Valid[Person==testperson]),
Baseline=sum(Success[Person!=testperson])/sum(Valid[Person!=testperson]))%>%
distinct(Your_Rate,.keep_all = TRUE)
plot_ly(comparison,y=~Your_Rate, type='bar')%>%
add_trace(y=~Baseline)
```
As I have it structured, a variable in the .Rmd defines the person that the calculations are being made for, and the only way I'm taking care of filenames is by manually saving a file with the person's name before knitting.
My guess at how to accomplish this is to:
Produce .Rmd files with the names of each person appended,(i.e PerfReport_a.Rmd, PerfReport_b.Rmd) and change the testperson variable in each file.
Run a script that knits each of these .Rmd files into a set of html files.
If I'm right about the general steps here, I have step 2 covered with a .R file that knits every .Rmd file within a directory.
files<-list.files("E:/Dashboards/",pattern = "[.]Rmd$")
files2<-as.data.frame(files)
files3<-files2%>%
mutate(filenow=paste0("E:/Dashboards/",files))
files4<-files3$filenow
for (f in files4) rmarkdown::render(f)
Any help with a means of generating the .Rmd files with the adjusted values for testperson would be greatly appreciated. If there is simply a better means of getting from a single, master .Rmd to the hundreds of personalized .html dashboards I'm looking to produce, I would love to learn that method, too!
Thank you in advance.
You can use yaml parameter params to get this right. You will need
one template (template.Rmd)
script to run the template (script.R)
Here is a small trivial example:
template.Rmd
---
title: no title
author: Roman
date: "`r Sys.Date()`"
params:
testperson: NA
---
```{r}
print(params$testperson)
```
```{r}
sessionInfo()
```
script.R
library(rmarkdown)
persons <- c("person1", "person2", "person3")
for (person in persons) {
rmarkdown::render(input = "template.Rmd",
output_file = sprintf("%s_report.html", person),
params = list(testperson = person)
)
}
This should populate your working folder with personX_report.html files (see screenshot below).

How to put a crossreference in Rbookdown?

I am not sure I understand this part from the documentation
the table label for a code chunk with the label foo will be tab:foo
Say I have a RMarkdown chunck such as
```{r mytable, echo=FALSE}
kable(df, booktabs=T)
```
I would consider mytabel as the label for the code chunck. That means I should be able to type a narrative that looks like:
This is my table \#ref(tab:mytable)
And the \#ref should reference the table number instead of the chucnk id. Instead I get a double (and clickable) ?? .What am I doing wrong?
In the second paragraph of the documention:
Like figures, tables with captions will also be numbered and can be referenced.
So you want to cross-reference a table, you must specify the caption argument.
You can create a empty RStudio project and or save following code as index.Rmd file. Or download
https://github.com/yihui/bookdown-minimal and replace the content of index.Rmd file with the following code. Then you can press Build Book button in the Build panel.
---
title: "A Book"
author: "Frida Gomam"
site: bookdown::bookdown_site
output:
bookdown::gitbook: default
---
# reference
This is my table \#ref(tab:mytable)
# table
```{r mytable, echo=TRUE}
knitr::kable(iris[1:10, ], booktabs=T, caption='A table of the first 10 rows of the mtcars data')
```

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!

How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?

I'd like to name my tables from R scripts without the automatic Table 1:... prefix when using xtable() or knitr::kable() in an .Rmd file. Output is a pdf document.
Here's a reproducible example from an .Rmd file:
---
title: "Suppress automatic table name and number"
output: pdf_document
---
```{r myirischunk, results = 'asis', tab.cap = NULL, echo = TRUE}
library(xtable)
print(knitr::kable(head(iris), caption = "I sure wish it would say Table 1.a"))
print(knitr::kable(head(iris), caption = "Please stop"))
print(xtable(head(iris), caption = "Same thing with xtable"))
```
I've seen similar questions with some suggestions here, but I can't seem to get it to work in an .Rmd file.
It turns out that I needed to add the following in the YAML section:
header-includes:
- \usepackage{caption}
AND the following somewhere before the code chunk:
\captionsetup[table]{labelformat=empty}
Now it works:
---
title: "Suppress automatic table name and number"
output: pdf_document
header-includes:
- \usepackage{caption}
---
\captionsetup[table]{labelformat=empty}
```{r myirischunk, results = 'asis', tab.cap = NULL, echo = TRUE}
print(knitr::kable(head(iris), caption = "Table 21.a - My very own table name"))
```
This has also been described here:
Get rid of captions using texreg in markdown
And yes, I'm a bit embarrased that I didn't find that answer straight away.
Anyway, thanks to daroczig for pointing me in the tex direction instead of trying to solve the problem using chunk options or something like that.
In case you also want figures the same way, modify the example by vestland to
---
title: "Suppress automatic table name and number"
output: pdf_document
header-includes:
- \usepackage[labelformat=empty]{caption}
---
and skip the \captionsetup{}.

R Markdown - variable output name

With one R markdown file, I would like to create different possible output pdf documents, where the output file name should be defined within the document. Is there any way to convince markdown to manipulate the output filename in such a way? Ideally I would like to pass the filename by an r chunk.
You can keep the simplicity of using the RStudio Knit button and reproducibility of a YAML header by using the undocumented knit hook to redefine what the button does (default function called is rmarkdown::render). The output_file parameter of the render function specifies the file name, so by setting it you override the standard behaviour of using the same prefix as the input filename.
e.g. to always output a file called myfile.pdf
knit: (function(inputFile, encoding) { rmarkdown::render(inputFile, encoding = encoding, output_file = file.path(dirname(inputFile), 'myfile.pdf')) })
The function can be an anonymous one-liner as well as imported from a package, as seen here with slidify.
You can set your own YAML headers (I don't know if this is generally advised anyway), accessible under rmarkdown::metadata$newheader but they don't seem available from within this sort of function as far as I can see.
As for passing file name in from an R chunk... if you're referring to code chunks below the YAML header, from my experience I don't think that's possible(?). Headers can contain inline R commands (single backtick-enclosed, starting with r), but seemingly not for this hook function.
Related:
Rmarkdown GitHub repo issue — output format-specific output_file
Blog post I wrote following this question [invalid link, domain for sale as of 20210216] / corresponding GitHub wiki notes
This is pretty much what I do:
rmarkdown::render('my_markdown_report.Rmd',
output_file = paste('report.', Sys.Date(),
'.pdf', sep=''))
I have three scripts - one pulls the data and process it, second created charts & tables for report. Third one creates report based on markdown file. Code you see above is the part of the third script
I played around with the Knitr-hook without fully understanding how it works and ran into an ugly workaround. The below coding seems to do the trick.
Would be nice if somebody can either explain why it works and/or if it can written less ugly.
For now I lost the shiny input screen but believe this can even be added later. The good thing is that the R-Studio Knit button can still be used.
Please note that the subtitle and the file name are both: This Works! even with space and exclamation mark. The file is saved as This Works!.pdf
The filename and subtitle are set by assigning the text to the object pSubTitle.
Note that the params are still in the YAML but are not resulting in a shiny popup screen as they are assigned in the Knitr-hook
---
params:
sub_title:
input: text
label: Sub Title
value: 'my_Sub_Title_and_File_Name'
title : "Parameterized_Title_and_output_file"
subtitle : "`r params$sub_title`"
output:
pdf_document:
keep_tex: false
knit: (
function(inputFile, encoding) {
pSubTitle <- 'This Works!'
rmarkdown::render(
input = inputFile,
encoding = encoding,
params = list(sub_title = pSubTitle),
output_file = pSubTitle) })
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. ....
My current solution for this and similar questions is through 2 scripts:
Script1: "xxx.md" file with flexible yaml header, similar to Floris Padt's. This header allows you to generate flexible pdf files with specified title, dates, and other features if you change the params. However, it could not specify flexible pdf names when you render it.
---
params:
feature_input: "XXXA"
date: "08/18/2022"
title: "`Test For `r params$feature_input``"
author: "You Name"
date: "`r params$date`"
output:
pdf_document:
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown and data process
```
#Get parameter from yaml head
input_para <- params$feature_input
input_para
```
Script2: "YYY.R", which specify params in xxx.md file, and specify pdf file names by output_file when rendering.
featureNames <- c("aaa", "bbb", "ccc")
setwd("path to xxx.md")
for (currentFeature in featureNames) {
rmarkdown::render("xxx.Rmd",
params = list(feature_input = currentFeature,
date = Sys.Date()),
output_file=paste0("output/",currentFeature))
}
You could update featureNames in yyy.R file, and run yyy.R to get the most flexible use of your xxx.md file.
This solution allows you to:
update yaml header parameters,
apply updated yaml parameters in your .md code chunk,
and save your pdf with specific and flexible names.

Resources