Selectively knitting R notebook - r

I would like to make long, well documented R-studio notebooks to completely document analyses, but then be able to knit either the full notebook or an abbreviated version for reports for different audiences. The long version for scientists and a short version as an executive summary.
I know about not running individual chunks, but is there a way to specify chunks together with sections of supporting text to be knit or not, and then somehow turn on or off the selective knitting?
This question shows how to use knit_exit() to exit knitting early, but I am looking for a way to go in and out multiple times through a document.

You can try the following code:
---
title: study sample
output: pdf_document
---
```{r beginning, echo = FALSE, include = FALSE}
echoaudience <- c("scientific", "executive")
```
```{r data1, echo = any(c("scientific","tested") %in% echoaudience)}
# a detailed report
```
```{r data2, echo = any(c("executive","brief") %in% echoaudience)}
# a brief summary
```
```{r data3, echo = any(c("myleftover","brief") %in% echoaudience)}
# some data only in my interest
```
It will return only the code you want to show, in this case data1 and data2. You can control the outputs.
```r
# a quite detailed info
```
```r
# a brief summary
```
Hope it helps.
Regards,
Alexis

Related

profvis stalling on function within markdown on linux

I would like to profile some functions in R, using profvis(), on a linux command line (outputting html)
I have tested this with the approach here, and it works. I saved the code in that link into a file named "test.Rmd". At the moment I am simply going into an R environment in linux and typing 'rmarkdown::render("test.Rmd")', and it produces a HTML file with the code chunks and the 'profvis' chart. Fine.
This is the code & function I want to profile;
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r packages}
library(data.table)
library(terra)
```
## profvis
This is an R Markdown document using profvis.
```{r settings}
# Functions used .
source("funcs.R")
```
```{r objects}
dt_a <- fread("a_table.csv")
dt_a <- fread("a_table.csv")
r_c <- rast("c_surface.tif")
```
```{r process}
myFunctoProf(year = 2020, arg_a = dt_a, arg_b = dt_b, arg_c = r_c,
req_string = "data/lookup_stuff.csv")
```
The above runs to completion in about 5 minutes, produces a HTML file, and outputs the results onto my computer (rasters). There are 3 further functions called within the myFunctoProf() function.
However, as soon as I put the profvis() function back in, as in the link above, the markdown seems to run indefinitely, it never completes and never errors and doesn't produce raster outputs or a HTML file.
```{r process}
profvis({
myFunctoProf(year = 2020, arg_a = dt_a, arg_b = dt_b, arg_c = r_c,
req_string = "data/lookup_stuff.csv")
})
```
Is the profvis() function struggling with the nested functionality? one of the functions called within myFunctoProf() is used in 'lapply', does that matter?
edit: wondered if it might be to do with the linux cluster using cores/nodes when using lapply(subFunc) within the main function call.

Getting flextable to knit to PDF

I feel like I've gone down a rabbit hole when all I want is some nice tables in my pdf. Long story, here goes:
I want to print some tables to a PDF from r markdown. I usually use Kable and it works fine. That being said, this table is going to have some really long values, and an unknown number of columns that get generated, and I was having a hard time specifying which column would be what width when I didn't know yet in kable. Anyhow, that led me to flextable.
When I knit to html, the table looks great, like so:
But I'm having trouble knitting to pdf. I understand, via other stack answers, that flextable's need to be saved as images to be plotted to pdf. So I have code like this:
ft <- flextable(x)
ft <- autofit(ft)
tf <- tempfile(fileext = ".png")
## Not run:
if( require("webshot2") ){
save_as_image(x = ft, path = "myimage.png")
}
plot(tf)
But at first it gave me the error that I didn't have the webshot2 package, so after some trouble I installed that (it didn't line up with my version of R (I'm on rstudio.cloud) and then when I try to run it now, it says
Am I missing something obvious? How do I save a flextable as an image and then plot it in my pdf?
I've also tried Joanna's solution here: Is it possible to generate the RTable (FlexTable) in pdf with RMarkdown? and r tells me could not find function "as.html". Even though both flextable and htmltools have been loaded.
P.s. providing reproducible data would be very long given all the code that generates the tables and the fact I need it to knit into a pdf, will provide rstudio.cloud link if anyone is interested
You can now produce PDF without the need of webshot package (flextable >= 0.6.0):
---
title: "Untitled"
output:
pdf_document:
latex_engine: xelatex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(flextable)
```
```{r}
ft <- flextable(head(airquality))
ft <- autofit(ft)
theme_vader(ft)
```

How to show code but hide output in RMarkdown?

I want my html file to show the code, but not the output of this chunk:
```{r echo=True, include=FALSE}
fun <- function(b)
{
for(a in b)
{print(a)
return(a * a)}
}
y <- fun(b)
```
When I run the code, i need the print to see the progress (it is quite a long function in reality).
But in the knitr file, I use the output in a further chunk, so I do not want to see it in this one (and there's no notion of progress, since the code has already been run).
This echo=True, include=FALSE here does not work: the whole thing is hidden (which is the normal behavior of include=FALSE).
What are the parameters I could use to hide the prints, but show my code?
As # J_F answered in the comments, using {r echo = T, results = 'hide'}.
I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!
You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.
Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
results = "hide")
```
Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.
```{r analysis, results="markup"}
# code here
```
The results = 'hide' option doesn't prevent other messages to be printed.
To hide them, the following options are useful:
{r, error=FALSE}
{r, warning=FALSE}
{r, message=FALSE}
In every case, the corresponding warning, error or message will be printed to the console instead.
```{r eval=FALSE}
The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.
For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)
For completely silencing the output, here what works for me
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code here
2 * 2
# etc etc
})})
```
The 5 measures used above are
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()
To hide warnings, you can also do
{r, warning=FALSE}

Rnotebook not showing code output for data frames

My code chunk output in Rnotebook is not appearing (as if not being run) when I try to view data frame results. I have to pass it through the pander() function to see the output print out. Is this something to do with knitr? I mention this because I set the options at the beginning to the following:
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE)
```
I have tried setting the options directly in the chunk but get the same unwanted result. Is there a setting I am not configuring correctly? I have to also mention that this is a behaviour that has been somehow inconsistent. That is, I may stop working on it and some time later the code output comes up somehow.
Here's an sample of the work code I am trying to run to copy paste into Rnotebook.
Setting the notebook workspace options
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE)
```
Loading the corresponding libraries and packages
```{r}
library(easypackages)
libraries("dplyr",
"ggplot2",
"caret",
"tidyverse",
"tidytext",
"ROCR",
"pander",
"knitr",
"broom")
```
Here's some sample data:
```{r}
library(readr)
attibm <- read_csv("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/mtcars.csv",
col_types = cols(Attrition = col_character()))
```
Seeing the structure. (This output is shown as expected)
```{r}
glimpse(attibm)
```
Preview the first ten rows (this is the output that doesn't show. Nothing happens)
```{r}
head(attibm)
```
This output doesn't show either. (Nothing happens)
```{r}
attibm %>%
summarise_if(is.integer, mean)
```
When I pass the pander function THEN it is shown.
```{r}
attibm %>%
summarise_if(is.integer, mean) %>%
pander()
```
This one is shown too
```{r}
pander(head(attibm))
```
I have checked the question posted: Output of numbers in R notebook, but I wasn't able to see the connection with this case.
I hope this is clear enough and that you can reproduce the code shown here. Any help on this issue will be highly appreciated.
The newest version of markdown is no longer compatible with pandocv2.
You can check your version of pandoc using
library(rmarkdown); pandoc_version()
If it's pandoc version you need the development version of markdown that you can download there
library(devtools); install_github("rstudio/rmarkdown")
To narrow down the issue of whether this is a problem with the newest version of pandoc, try checking wether the .md produced is correct by adding
---
output:
html_notebook
keep_md: true
---
I had a similar problem which data.frame and DT:data.table wouldn't show any output.
this post helped me.
I found that the cause of problem was my mis-typing in .rmd file name including a non-ASCII character! as soon as i removed it the problem resolved.
Hope this helps others too

Data and plots from different chunks

I am creating a Word report with R studio, markdown and knitr and I am having some troubles.
My r code includes several chunks, becauase between chunks, I want to include the text my report should include.
The problem I have is that: if use a single chunk, then the report is ok, but I can't include text/comments to be written in the report, unless I print also the code (right?). But if I use multiple chunks, then, when compiling, plots are not included in the report and warning messages appear:
pandoc.exe: Could not find image `Scriptv01_files/figure-docx/4.PLOTS-1.png', skipping...
It only works with HTML output: report includes all plots, but not with DOC nor PDF output.
I think the issue is that the data object is created in a different chunk, but I have tried 'cache' and 'autodep' options with no success.
How can this be done? What's the problem with the code?
Many thanks!
Here I provide a code example:
---
output: word_document
---
# PROJECT: IRIS STUDY
#### Statistical Analysis
```{r setup}
require(knitr)
opts_chunk$set(echo = TRUE, message=FALSE, warning=FALSE, comment='')
```
```{r read data}
dataset<-iris
```
### Data Descriptive by Iris Specie
```{r 4. ANALYSE DATA - DATA DESCRIPTION BY SPECIE}
require(ggplot2)
ggplot(dataset, aes(Species)) + geom_bar(aes(fill=Species))+
labs(x = "Species", y = "Number of Flowers")+ ggtitle("Fisher's Iris data set")
```
knitr uses the chunk name as part of the image file name. The chunk name 4. ANALYSE DATA - DATA DESCRIPTION BY SPECIE is invalid and is the reason why the plot is not being created. Replacing the name by a valid name solves the problem:
Avoid spaces and periods . in chunk labels and directory names [Source]

Resources