As known in RMarkdown code chunks can be named like this:
```{r chunkname}
plot(x,y)
```
Is it possible to showing chunkname in output document?
You can use knitr::opts_current$get()$label
example:
```{r cars}
library(knitr)
opts_current$get()$label
plot(cars)
```
It will also work outside of a chunk, in an inline r code. It will then output the label of the last chunk.
You can of course save the labels in a vector to use them later, for instance with a custom hook:
```{r knitr_setup}
library(knitr)
ll <- opts_current$get()$label
knit_hooks$set(label_list = function(before, options, envir) {
if(before) ll <<- c(ll,opts_current$get()$label)
})
opts_chunk$set(label_list=TRUE)
```
ll will then contain the list of chunk labels. However, you cannot access the names of chunks not yet ran.
Related
The aim is to create a flexdashboard layout in an markdown file. File is in rows orientation and then the layout contains multiple rows one under another. The goal is to have one of the layout section and accompanying chunk not executed/displayed based on a predefined boolean condition. I was able to incorporate a boolean to not include the chunk code in output but can't find any results on a conditional layout.
Things to note the final result is a standalone file so shiny solutions are not possible. AFAIK
Current Result and needed result
What I've come up with so far just keeps the layout there with the title instead of removing everything.
the variable series35 is what is being used as a boolean to make the chunk not produce results. How can the
`row`
`--------------------------------------`
lines also be conditionalised (if that's a word) aka not create a new layout section when series35 is FALSE
row
-------------------------------------
###`r Title 1`
```{r, echo=FALSE, results='asis'}
chunk code
```
row
-------------------------------------
###`r Title 2`
```{r, echo=FALSE, results='asis', eval = series35}
chunk code (suppressed when series35 is FALSE)
```
row
-------------------------------------
###`r Title 3`
```{r, echo=FALSE, results='asis'}
chunk code
```
row
-------------------------------------
###`r Title 4`
```{r, echo=FALSE, results='asis'}
chunk code
```
row {data-height=50}
-------------------------------------
I ended up after much more searching finding a knitr question that gave me a solution
```{r, eval = series35}
asis_output("row")
asis_output("-------------------------------------")
asis_output("###`Title 2`")
```
```{r, echo=FALSE, results='asis', eval = series35}
chunk code (suppressed when series35 is FALSE)
```
It worked nicely as a quick addition. I didn't try joshpk's method as yet but it does seem like a potentially clean option.
You can wrap that section in comments that are controlled by your series35. Something like this (if you can provide a reproducible example then it will be easier to provide something that meets your requirements but hopefully this helps).
`r if(series35 == FALSE) {"\\begin{comment}"} else {NULL}`
###`r Title 2`
```{r, echo=FALSE, results='asis', eval = series35}
chunk code (suppressed when series35 is FALSE)
```
`r if(series35 == FALSE) {"\\end{comment}"} else {NULL}`
I am looking to print multiple flextables in a single R Markdown document. This is not challenging when using html output, but I need Word output.
With html output, the following R Markdown code (example taken from https://davidgohel.github.io/flextable/articles/offcran/examples.html#looping-in-r-mardown-documents) produces a document with multiple Flextables:
---
output:
html_document: default
---
```{r}
library(htmltools)
library(flextable)
ft <- flextable(head(iris))
tab_list <- list()
for(i in 1:3){
tab_list[[i]] <- tagList(
tags$h6(paste0("iteration ", i)),
htmltools_value(ft)
)
}
tagList(tab_list)
```
I have been unable to get an equivalent output using Word document output.
The solution proposed in
How to knit_print flextable with loop in a rmd file similarly works fine with html output, but I have failed to get this to render correctly with Word output.
Any advice on a R Markdown Word document output equivalent of the above example would be very helpful!
You need to use flextable::docx_value and the chunk option results='asis'
---
title: "Untitled"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r results='asis'}
ft <- flextable(head(iris))
for(i in 1:3){
cat("<w:p/>")## add this to add an empty new paragraph between tables
flextable::docx_value(ft)
}
```
I'm trying to generate a rmarkdown chunk using code. I've read similar questions and their solutions, such as using pander or using cat. I just can't seem to generate it. I also tried knitting the output manually. Here's an example of a Rmd file:
---
title: "test"
output: pdf_document
---
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
"2+2",
"```")
pander::pander(txt)
```
When I knit this, I get a verbatim {r} 2+2. I would like to see the number four instead. In my real example, I'm using bookdown and trying to generate a block2 chunk.
Any ideas how to generate this chunk that gets evaluated as R code?
Does this do what you want?
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
2+2,
"```")
pander::pander(txt)
```
This evalutates to
```{r} 4 ```
in your markdown document.
You using a string literal "2+2" as opposed to the expression 2+2. This is the first issue, I guess.
If you want it correctly parsed you need to add an sep = "\n" argument to paste or manually add the newline breaks.
I.e.
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}\n",
2+2,
"\n```", sep = "")
pander::pander(txt)
```
This evalutates to
```{r}
4
```
which is interpreted as R code in the markdown document.
I'm after a way to render an Rmd document (that contains references to various "child" files) to a self-contained R Notebook without these dependencies.
At the moment, the .Rmd code chunks are located throughout a number of .R, .py and .sql files and are referenced in the report using
```{r extraction, include=FALSE, cache=FALSE}
knitr::read_chunk("myscript.R")
```
followed by
```{r chunk_from_myscript}
```
as documented here.
I've done this to avoid code duplication and to allow for running the source files separately however these code chunks are only executable in the report via a call to knit or render (when read_chunk is run and the code chunk is available).
Is there a way to spin-off an Rmd (prior to knitting) with
just these chunks populated?
This function
rmarkdown::render("report.Rmd", clean = FALSE)
almost gets there as it leaves the markdown files behind whilst removing extraction and populating chunk_from_myscript however as these files are straight markdown, the chunks are no longer executable and the chunk options are missing. It obviously also doesn't include chunks where eval=TRUE, echo=FALSE which would be needed to run the resulting notebook.
I've also looked at knitr::spin however this would mean disseminating the contents of the report to every source file and isn't terribly ideal.
Reprex
report.Rmd
---
title: 'Report'
---
```{r read_chunks, include=FALSE, cache=FALSE}
knitr::read_chunk("myscript.R")
```
Some documentation
```{r chunk_from_myscript}
```
Some more documentation
```{r chunk_two_from_myscript, eval=TRUE, echo=FALSE}
```
myscript.R
#' # MyScript
#'
#' This is a valid R source file which is formatted
#' using the `knitr::spin` style comments and code
#' chunks.
#' The file's code can be used in large .Rmd reports by
#' extracting the various chunks using `knitr::read_chunk` or
#' it can be spun into its own small commented .Rmd report
#' using `knitr::spin`
# ---- chunk_from_myscript
sessionInfo()
#' This is the second chunk
# ---- chunk_two_from_myscript
1 + 1
Desired Output
notebook.Rmd
---
title: 'Report'
---
Some documentation
```{r chunk_from_myscript}
sessionInfo()
```
Some more documentation
```{r chunk_two_from_myscript, eval=TRUE, echo=FALSE}
1 + 1
```
Working through your reprex I now better understand the issue you are trying to solve. You can knit into an output.Rmd to merge your report and scripts into a single markdown file.
Instead of using knitr::read_chunk, I've read in with knitr::spin to cat the asis output into another .Rmd file. Also note the params$final flag to allow rendering the final document when set as TRUE or allowing the knit to an intermediate .Rmd as FALSE by default.
report.Rmd
---
title: "Report"
params:
final: false
---
```{r load_chunk, include=FALSE}
chunk <- knitr::spin(text = readLines("myscript.R"), report = FALSE, knit = params$final)
```
Some documentation
```{r print_chunk, results='asis', echo=FALSE}
cat(chunk, sep = "\n")
```
to produce the intermediate file:
rmarkdown::render("report.Rmd", "output.Rmd")
output.Rmd
---
title: "Report"
---
Some documentation
```{r chunk_from_myscript, echo=TRUE}
sessionInfo()
```
With the secondary output.Rmd, you could continue with my original response below to render to html_notebook so that the document may be shared without needing to regenerate but still containing the source R markdown file.
To render the final document from report.Rmd you can use:
rmarkdown::render("report.Rmd", params = list(final = TRUE))
Original response
You need to include additional arguments to your render statement.
rmarkdown::render(
input = "output.Rmd",
output_format = "html_notebook",
output_file = "output.nb.html"
)
When you open the .nb.html file in RStudio the embedded .Rmd will be viewable in the editing pane.
Since neither knitr::knit nor rmarkdown::render seem suited to rendering to R markdown, I've managed to somewhat work around this by dynamically inserting the chunk text into each empty chunk and writing that to a new file:
library(magrittr)
library(stringr)
# Find the line numbers of every empty code chunk
get_empty_chunk_line_nums <- function(file_text){
# Create an Nx2 matrix where the rows correspond
# to code chunks and the columns are start/end line nums
mat <- file_text %>%
grep(pattern = "^```") %>%
matrix(ncol = 2, byrow = TRUE)
# Return the chunk line numbers where the end line number
# immediately follows the starting line (ie. chunk is empty)
empty_chunks <- mat[,1] + 1 == mat[,2]
mat[empty_chunks, 1]
}
# Substitute each empty code chunk with the code from `read_chunk`
replace_chunk_code <- function(this_chunk_num) {
this_chunk <- file_text[this_chunk_num]
# Extract the chunk alias
chunk_name <- stringr::str_match(this_chunk, "^```\\{\\w+ (\\w+)")[2]
# Replace the closing "```" with "<chunk code>\n```"
chunk_code <- paste0(knitr:::knit_code$get(chunk_name), collapse = "\n")
file_text[this_chunk_num + 1] %<>% {paste(chunk_code, ., sep = "\n")}
file_text
}
render_to_rmd <- function(input_file, output_file, source_files) {
lapply(source_files, knitr::read_chunk)
file_text <- readLines(input_file)
empty_chunks <- get_empty_chunk_line_nums(file_text)
for (chunk_num in empty_chunks){
file_text <- replace_chunk_code(file_text, chunk_num)
}
writeLines(file_text, output_file)
}
source_files <- c("myscript.R")
render_to_rmd("report.Rmd", "output.Rmd", source_files)
This has the added benefits of preserving chunk options and working
with Python and SQL chunks too since there is no requirement to evaluate
any chunks in this step.
I have a chuck
```{r}
Item <- melt(Item)
```
Which creates an output :
## Using as id variables
How do I evaluate the code but suppress this output.
{r, warning=FALSE, message=FALSE}
Item <- melt(Item)
Details are documented here : https://www.rstudio.com/wp-content/uploads/2015/02/rmarkdown-cheatsheet.pdf