I am new to Stackoverflow - so please excuse any possible strangeness in my post.
I have a simmilar question as Tom, posted here.
I want to save a pdf created by markdown in a specific directory. After several unsuccessful attempts (including a frustrating chat with GPT), I followed starjas instructions in the post mentioned, yet unsuccessfully.
Here's my YAML header:
---
title: 'MyTitle'
subtitle: 'Analysis XYZ'
author: "Boris et al."
date: "2023-01-22"
knit: (function(input, encoding) {
rmarkdown::render(input,
encoding = "UTF-8",
output_dir = "05-Reports")})
output: pdf_document
---
… and here some code snippets from the scripts main body:
knitr::opts_chunk$set(echo = FALSE, message = TRUE)
source("02-Scripts/03-LogMod-6-plot.R", local = knitr::knit_global())
{r model results} model6.res.table <- simple_kable <- knitr::kable(model6.res, format = "pipe") model6.res.table
Here's the error message I get:
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
Calls: <Anonymous> ... eval_with_user_handlers -> eval -> eval -> source -> file
Execution halted
I believe that the problem has to do something with R not being able to find the output-directory specified (05-Reports). But I have no clue why, as this output-directory is within the working directory:
getwd()
[1] "/Users/my-User/Documents/studyXYZ/1-XYZdata/6-R/studyXYZ-R-Project"
list.files()
[1] "01-Data" "02-Scripts" "03-Outputs"
[4] "04-Plots" "05-Reports" "studyXYZ-R-Project.Rproj"
Maybe important to know: I am working with a R-project. Furthermore, in the Global Options under R Markdown, I set "Evaluate chunks in directory:" "Project", as Julius Diel mentioned in a thread regarding a similar topic:
"Error "cannot open the connection" in executing "knit HTML" in RStudio"
Before setting R's Global Options like this, I had other issues regarding the scource()-command from my markdown-script adressing the R-scripts containing the analysis-commands. Now the scourcing works fine and I get the results as expected when conducting the markdown script without specifying the output directory (in html and pdf). It's just that the pdf won't be saved where I want it.
Does anyone have a clue what causes this problem?
I didn't know about the option Evaluate chunks in directory: "Project". Previously, I used the following in the setup chunk:
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
However, this option is ignored (as well as the option set in RStudio) when using rmarkdown::render in the header of the document. You need to set knit_root_dir to define the root directory from which you the can specify relative paths in source used in your rmarkdown document:
knit: (function(input, encoding) {
rmarkdown::render(input,
output_dir = "05-Reports",
knit_root_dir = rprojroot::find_rstudio_root_file())})
Related
I'd like to run an R script before building a bookdown book. The script runs purl() on specific Rmd Files which again are included in the book (an thus need an update since the Rmd Files might have changed).
I'd like to automatize this since it's easy to forget running the script before building the book. Also, I'd like to stick with the "build book" button since this is very convenient.
I tried including the script in the index.Rmd File, but this lead to a "duplicate label" issue as described by this unanswered question. The error described by #Adam M. Wilson is persistent when using bookdown even when completely omitting named chunks.
He're a minimal example using a minimal example of a bookdown project. The error is posted below.
Is there a workaround to this issue? Either (a) a solution for running purl() within a chunk or (b) running an R-script automatically prior to building the book?
---
title: "A Book"
author: "Frida Gomam"
site: bookdown::bookdown_site
documentclass: book
output:
bookdown::gitbook: default
bookdown::pdf_book: default
---
# Hello World
```{r}
library(stringr)
rmds <- list.files(pattern = ".Rmd")
for (file in rmds){
file_r <- gsub("Rmd","R",file)
if(file.exists(file_r)){
file.remove(file_r)
}
knitr::purl(file,documentation = 0,output = file_r)
}
```
Hi.
Bye.
And here's the error message:
Quitting from lines 14-27 (index.Rmd)
Error in parse_block(g[-1], g[1], params.src) :
duplicate label 'unnamed-chunk-1'
Calls: <Anonymous> ... process_file -> split_file -> lapply -> FUN -> parse_block
Please delete _main.Rmd after you finish debugging the error.
Execution halted
Exited with status 1.
You use same name in the markdown file. For example
{r relationship between gender and health}
....
....
{r relationship between gender and health}
....
....
Then you will meet an error when knit
I have tried to attach bibliography.bib, nature.csl files by using knitcitations packages on myPkg_vignette.Rmd, but when I execute the .Rmd file, I got following error:
pandoc-citeproc.exe: Could not find bibliography.bib
pandoc.exe: Error running filter pandoc-citeproc
Filter returned error status 1
Error: pandoc document conversion failed with error
I looked into knitcitations manual and how to attach .csl, .bib file by handy, but I got warning and can't attach these files on myPkg_vignette.Rmd.
Edit :
This is context of bibliography.bib:
#article{Vahid_Jalili_Musera_2015,
title = "MuSERA: Multiple Sample Enriched Region Assessment",
author = {Vahid Jalili, Matteo Matteucci, Marco Masseroli, Marco J. Morelli},
journal = "Briefings in Bioinformatics",
year = "2016",
pages = "1-15",
url = {http://bib.oxfordjournals.org/content/early/2016/03/23/bib.bbw029.abstract?keytype=ref&ijkey=8IlROGziM9XA7NS},
doi = "10.1093/bib/bbw029 ",
}
How can I attach bibliography.bib, nature.csl on package's vignette easily ? I read some post in SO and I confused about the given solution. I am quite new with using knitcitations packages, and I may get wrong with attaching .bib, .csl files in right way. Can any one help me out how to address this issues in Rstudio ? Any idea ? Thanks a lot :)
NEW EDIT :
I've read this post and followed the solution :
setwd('C:/Users/me/Documents/myPkg')
Sys.setenv(TEXINPUTS=getwd(),
BIBINPUTS=getwd(),
BSTINPUTS=getwd())
but bibliography.bib is not printed in .Rmd file. I changed the global option for weaving Rnw file to knitr. How can I print out bibliography on .Rmd file ? Any further help please ?
As with Dirk, it just works for me. Maybe you didn't put the YAML together properly, or maybe you never cited anything. Here's a sample document that works with your bib file:
---
title: "Biblio Example"
output: html_document
bibliography: bibliography.bib
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Here's Some Text
This text cites the paper: [#Vahid_Jalili_Musera_2015].
## References
The bibliography will appear by magic at the end of the document, just
below this text.
See http://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html for more details.
For me the problem was that my .bib file was listed in .Rbuildignore. Removing the entry solved the problem.
According to the r-pkg-dev mailing list answer from Duncan Murdoch, .Rbuildignore is "case-insensitively against the file and directory names relative to the top-level package source directory".
Therefore the entry xxx.bib ignored all .bib files recursively in my package directory and the error was thrown.
I am trying to modify the behavior of RStudio's knit button, by changing the directory to which it writes the output of knitting the Rmd file. I have started with this answer, but instead of having the filename given by a fixed string, I'd like to have the output filename based on the Rmd filename. However, the variable inputFile includes the full path to the Rmd file. Is there a way to get only the filename without the path?
The header I am working with that produces the full path+filename where I'd like just the filename (test2 is a directory that I created in the current working directory):
---
knit: (function(inputFile, encoding) {rmarkdown::render(inputFile,encoding=encoding, output_file=file.path(dirname(inputFile), "test2", paste0(substr(inputFile,1,nchar(inputFile-4),".html"))) })
output: html_document
---
I'm still interested in a command that would directly give me the input filename, as specified in the question, but I found a workaround for the particular issue, using regex in the substr call, based on this:
knit: (function(inputFile, encoding) {rmarkdown::render(inputFile,encoding=encoding, output_file=file.path(dirname(inputFile), "test2", paste0(substr(inputFile,rev(gregexpr("/", inputFile)[[1]])[1]+1,nchar(inputFile)-4),".html"))) })
Nowadays, knitr comes with a function current_input() that gives you the name of the Rmd-file as a string. And tools::file_path_sans_ext() will remove the extension.
But to solve the exact problem of the OP, there are probably better options today, for example, knitr options, the package ezknitr, RStudio "Knit Directory" button, or here::here().
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.
I have a collection of R scripts in a directory and want to compile them all
to HTML, as I might do using R Studio Compile Notebook manually, but with some control over the CSS styling.
Each file has a minimal YAML header and a bit of markup, as shown below, and I don't want to introduce additional complexity in the scripts with chunk options except where absolutely necessary.
#' ---
#' title: "Tests for association in two-way tables"
#' author: "Michael Friendly"
#' ---
#' ## Load and examine data
library(vcdExtra)
data(SexualFun)
SexualFun # show the table
...
I'm confused about which tools to use to compile a single file in this way--- spin|knit2html, markdownToHTML, etc. Once I get this right, I can use something like apply() to do it for my list of files, files <- list.files(pattern="*.R$").
Here's what I've tried to compile one file, with some additional control:
library(knitr)
options(markdown.HTML.options = markdownHTMLOptions(stylesheet = "markdown.css"))
knit_theme$set("seashell")
opts_chunk$set(fig.align="center")
spinone <- function(file, outdir="output/") {
fn <- knitr:::sans_ext(file)
#+ suppressmessages, include=FALSE
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
spin(file)
Rmd <- knitr:::sub_ext(file, "Rmd")
out <- paste0(outdir, knitr:::sub_ext(file, "html"))
knit2html(Rmd, output=out)
}
But it doesn't work correctly. I get:
> spinone("sexfun-chisq.R")
processing file: sexfun-chisq.Rmd
...
|.................................................................| 100%
ordinary text without R code
output file: sexfun-chisq.md
Error in readLines(if (is.character(input2)) { :
cannot open the connection
In addition: Warning message:
In readLines(if (is.character(input2)) { :
cannot open file 'sexfun-chisq.Rmd': No such file or directory
Actually, sexfun-chisq.html is produced, but it doesn't have the YAML header and doesn't use my style options.
Use spin(file, knit = FALSE) so that the Rmd file will not be deleted (see the precious argument in ?spin).