profvis stalling on function within markdown on linux - r

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.

Related

Display Block of R Code in Knitr With Evaluation Turned Off

I am writing a document with fairly resource intensive R code. I want to prevent execution of one block of R code in knitr which is giving me document timeout error in Overleaf.
In R studio, this can be done using eval = FALSE. I want to recreate this in knitr. So far, the only way I have found is to suppress errors using <<setup, include=FALSE, cache=FALSE>>= muffleError <- function(x,options) {} but it only works on the entire document.
I specifically want to prevent evaluation but show the R code.
Is this what you want to do, or have I misunderstood? The eval = FALSE is in one code chunk and the second chunk still plots.
---
title: "A Test Knit"
output: html_document
---
## Show code but don't run
```{r, eval = FALSE}
summary(cars)
```
## Run and render plot
```{r}
plot(pressure)
```

Selectively knitting R notebook

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

knitr and knit_print with HTML output - dispatch not working

I have a shiny app (radiant.data) that uses knitr to generate reports viewable inside the application (R > Report). Because the output is displayed inside a shiny app I need a render function for something like a DT table to be displayed (i.e., convert to shiny.render.function). This all works fine.
Now, however, I want to use a custom print method to handle rendering so I can just use DT::datatable(mtcars) with knitr and knit_print.datatables to generate a shiny.render.function.
Below some example R-markdown that includes the knit_print.datatables function i'm using. chunk1 and chunk2 show a shiny.render.function as intended but the chunk6 shows nothing. If screenshot.force = TRUE I get a screenshot from chunk6 but that is not what I want either.
Example R-markdown to be processed with knitr::knit2html
```{r chunk1}
knitr::opts_chunk$set(screenshot.force = FALSE)
DT::renderDataTable(DT::datatable(mtcars))
```
```{r chunk2}
knit_print.datatables <- function(object, ...) {
DT::renderDataTable(object)
}
```
```{r chunk3}
knit_print <- knitr::knit_print
knit_print.datatables(DT::datatable(mtcars))
```
```{r chunk4}
getS3method("knit_print", "datatables")
```
```{r chunk5}
class(DT::datatable(mtcars))
```
```{r chunk6}
DT::datatable(mtcars)
```
I realize the R-markdown above, although reproducible if you have knitr and DT installed, looks a bit weird but when I export the knit_print.datatables function properly I get the same result in my application (see example output below).

sourcing and displaying R source code in R Markdown without executing

I am writing a book in R Markdown. I saved a lot of code in separate .R files. For didactical purpose I need to show the whole file's contents without actually running it.
e.g., I would like that
r my_r_chunk
source("./code/mycodefile.R")
```
would be rendered displaying the whole content of mycodefile.R without actually executing it.
Check out ?knitr::read_chunk
First, assign a label to the script using the syntax ## ---- your_label ---- by placing it in the first line of the script which is called foo.R
foo.r
## ---- your_label ----
print("Hello World")
1:10
After assigning the script a label, you can then read_chunk the script in an uncached chunk. Finally you reference the contents in a subsequent (cached) chunk using the eval = FALSE chunk option.
your_Rmd_file.Rmd
---
output: pdf_document
---
```{r cache=FALSE, echo = FALSE}
library(knitr)
read_chunk('foo.R')
```
```{r your_label, cache = TRUE, eval=FALSE}
```

R knitr: Possible to programmatically modify chunk labels?

I'm trying to use knitr to generate a report that performs the same set of analyses on different subsets of a data set. The project contains two Rmd files: the first file is a master document that sets up the workspace and the document, the second file only contains chunks that perform the analyses and generates associated figures.
What I would like to do is knit the master file, which would then call the second file for each data subset and include the results in a single document. Below is a simple example.
Master document:
# My report
```{r}
library(iterators)
data(mtcars)
```
```{r create-iterator}
cyl.i <- iter(unique(mtcars$cyl))
```
## Generate report for each level of cylinder variable
```{r cyl4-report, child='analysis-template.Rmd'}
```
```{r cyl6-report, child='analysis-template.Rmd'}
```
```{r cyl8-report, child='analysis-template.Rmd'}
```
analysis-template.Rmd:
```{r, results='asis'}
cur.cyl <- nextElem(cyl.i)
cat("###", cur.cyl)
```
```{r mpg-histogram}
hist(mtcars$mpg[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders"))
```
```{r weight-histogam}
hist(mtcars$wt[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders"))
```
The problem is knitr does not allow for non-unique chunk labels, so knitting fails when analysis-template.Rmd is called the second time. This problem could be avoided by leaving the chunks unnamed since unique labels would then be automatically generated. This isn't ideal, however, because I'd like to use the chunk labels to create informative filenames for the exported plots.
A potential solution would be using a simple function that appends the current cylinder to the chunk label:
```r{paste('cur-label', cyl, sep = "-")}
```
But it doesn't appear that knitr will evaluate an expression in the chunk label position.
I also tried using a custom chunk hook that modified the current chunk's label:
knit_hooks$set(cyl.suffix = function(before, options, envir) {
if (before) options$label <- "new-label"
})
But changing the chunk label didn't affect the filenames for generated plots, so I didn't think knitr was utilizing the new label.
Any ideas on how to change chunk labels so the same child document can be called multiple times? Or perhaps an alternative strategy to accomplish this?
For anyone else who comes across this post, I wanted to point out that #Yihui has provided a formal solution to this question in knitr 1.0 with the introduction of the knit_expand() function. It works great and has really simplified my workflow.
For example, the following will process the template script below for every level of mtcars$cyl, each time replacing all instances of {{ncyl}} (in the template) with its current value:
# My report
```{r}
data(mtcars)
cyl.levels <- unique(mtcars$cyl)
```
## Generate report for each level of cylinder variable
```{r, include=FALSE}
src <- lapply(cyl.levels, function(ncyl) knit_expand(file = "template.Rmd"))
```
`r knit(text = unlist(src))`
Template:
```{r, results='asis'}
cat("### {{ncyl}} cylinders")
```
```{r mpg-histogram-{{ncyl}}cyl}
hist(mtcars$mpg[mtcars$cyl == {{ncyl}}],
main = paste({{ncyl}}, "cylinders"))
```
```{r weight-histogam-{{ncyl}}cyl}
hist(mtcars$wt[mtcars$cyl == {{ncyl}}],
main = paste({{ncyl}}, "cylinders"))
```
If you make all chunks in your ** nameless, i.e. ```{r} it works. This, of course, is not very elegant, but there are two issues preventing you from changing the label of the current chunk:
A file is parsed before the code blocks are executed. The parser already detects duplicate labels, before any code is executed or custom hooks are called.
The chunk options (inc. the label) are processed before the hook is called (logical: it's an option that triggers a hook), so the hook cannot change the label anymore.
The fact that unnamed blocks work is that internally they get the label unnamed-chunk-+chunk number.
Blocks cannot have duplicate names as internally knitr references them by label. A fix could be to make knitr add the chunk number to all chunks with duplicate names. Or to reference them by chunk number instead of label, but that seems to me a much bigger change.
There is a similar question posed here I was able to programmatically create r chunks and knit the outputs for use in a flexdashboard (quite useful) based on an arbitrary list of input plots using the knit_expand(text=) and r paste(knitr::knit(text = paste(out, collapse = '\n'))) methods.

Resources