Compile quarto document in temporary directory in R - r

I want to compile a template quarto report in a temporary directory. In the real case, the template is in an R package, and therefore has to compiled in a temporary directory. But I get the following error:
# This will create a file named "template.qmd" in the current folder.
# Used in: the "template.qmd" is a parametrized report and in a package. The report
# will be compiled in a temporary directly which will be cleaned afterwards.
f <- c("---", "title: \"Test\"", "format: html", "---", "", "## Set a variable",
"", "```{r}", "OK <- FALSE", "```", "", "## Running Code depending on value of `OK`",
"", "```{r}", "#| eval: !expr OK", "print(\"OK is TRUE - otherwise you won't see anything here.\")",
"```", "")
writeLines(f, "template.qmd")
name <- "Test_Report"
output_format <- "html"
output_file <- paste0(name, ".html")
tmpdir <- tempfile()
dir.create(tmpdir)
template <- file.path(tmpdir, "template.qmd")
file.copy(
file.path(".", "template.qmd"),
template
)
report <- quarto::quarto_render(
input = template,
output_format = output_format,
output_file = output_file
)
# Here the error occurs:
#
# processing file: template.qmd
# |.............. | 20%
# ordinary text without R code
#
# |............................ | 40%
# label: unnamed-chunk-1
# |.......................................... | 60%
# ordinary text without R code
#
# |........................................................ | 80%
# label: unnamed-chunk-2 (with options)
# List of 1
# $ eval: logi FALSE
#
# |......................................................................| 100%
# ordinary text without R code
#
#
# output file: template.knit.md
#
# pandoc --output ../../../../../../../Users/rainerkrug/tmp/test/Test_Report.html
# to: html
# standalone: true
# section-divs: true
# html-math-method: mathjax
# wrap: none
# default-image-extension: png
#
# metadata
# document-css: false
# link-citations: true
# date-format: long
# lang: en
# title: Test
#
# pandoc: ../../../../../../../Users/rainerkrug/tmp/test/Test_Report.html: openFile: does not exist (No such file or directory)
# Error in `processx::run(quarto_bin, args, echo = TRUE)`:
# ! System command 'quarto' failed
# ---
# Exit status: 1
# stdout & stderr: <printed>
# ---
# Type .Last.error to see the more details.
# And I would like to continuye as follows:
file.copy(
file.path(tmpdir, output_file),
file.path(".", output_file),
)
unlink(tmpdir)
Session Info:
> sessionInfo()
R version 4.2.2 (2022-10-31)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.1
Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/lib/libRlapack.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] Rcpp_1.0.9 ps_1.7.2 digest_0.6.31 later_1.3.0 R6_2.5.1
[6] jsonlite_1.8.4 evaluate_0.19 rlang_1.0.6 cli_3.6.0 rstudioapi_0.14
[11] rmarkdown_2.19 tools_4.2.2 yaml_2.3.6 xfun_0.36 fastmap_1.1.0
[16] compiler_4.2.2 processx_3.8.0 htmltools_0.5.4 knitr_1.41 quarto_1.2
>
Is this a bug in quarto, or am I doing something obvious wrong?

There seems to be a bug in quarto / panda on Mac, as it works on Ubuntu. The problem is the argument output_file = output_file. As soon as it is present, the Mac implementation fails. I solved it wit the following:
f <- c("---", "title: \"Test\"", "format: html", "---", "", "## Set a variable",
"", "```{r}", "OK <- FALSE", "```", "", "## Running Code depending on value of `OK`",
"", "```{r}", "#| eval: !expr OK", "print(\"OK is TRUE - otherwise you won't see anything here.\")",
"```", "")
writeLines(f, "template.qmd")
name <- "Test_Report"
output_format <- "html"
output_file <- paste0(name, ".html")
tmpdir <- tempfile()
dir.create(tmpdir)
template <- file.path(tmpdir, paste0(name, ".qmd"))
file.copy(
file.path(".", "template.qmd"),
template
)
report <- quarto::quarto_render(
input = template,
output_format = output_format
)
fn <- c(paste0(name, ".html"), paste0(name, "_files"))
file.copy(
file.path(tmpdir, fn),
file.path("."),
recursive = TRUE
)
unlink(tmpdir)

Related

Cannot release memory with knitr

I have an issue with knitr where I run can the code in the console without a problem but run out of memory when I knit the document. The markdown document is similar to
---
title: "xyz"
output:
html_document:
toc: true
date: "`r format(Sys.time(), '%d %B, %Y')`"
author: Me
bibliography: ../ref.bib
---
```{r setup, include = FALSE, cache = FALSE}
options(width = 100, digits = 3, scipen = 8)
knitr::opts_chunk$set(
error = FALSE, cache = FALSE,
cache.path = "some-path-cache/", fig.path = "some-path-fig/",
warnings = TRUE, message = TRUE, dpi = 128, cache.lazy = FALSE)
```
[some code]
```{r load_dat}
big_dat <- func_to_get_big_dat()
some_subset <- func_to_get_subset()
```
[some code where both big_dat and some_subset is used, some objects are assigned and some are subsequently removed with rm]
```{r reduce_mem}
dat_fit <- big_dat[some_subset, ]
rm(big_dat)
```
```{r log_to_show}
sink("some-log-file")
print(gc())
print(sapply(ls(), function(x) paste0(class(get(x)), collapse = ";")))
print(sort(sapply(ls(), function(x) object.size(get(x)))))
sink()
```
```{r some_chunk_that_requires_a_lot_of_memory, cache = 1}
...
```
When I knit the document using knitr then I run out of memory in the some_chunk_that_requires_a_lot_of_memory and the content of some-log-file is
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 3220059 172 5684620 304 5684620 304
Vcells 581359200 4436 1217211123 9287 981188369 7486
[output abbreviated (the other variables are "function"s, "character"s, and "matrix"s]
dat_fit X1 some_subset
"data.frame" "integer" "integer"
[output abbreviated]
X1 some_subset dat_fit
5235568 5235568 591631352
so the objects in the .GlobalEnv far from sums to the 4436 MB (there are not many objects and they far smaller than 50 MB each). Running the code in the console does not yield any issues and the print(gc()) shows a much smaller figure.
My questions are
Can I do something to figure out why I use much more memory when I knit the document? Clearly, there must be assigned some objects somewhere that takes up a lot of space. Can I find all assigned objects and check their size?
Do you have some suggestion why gc release less memory when I knit the document? Is there somewhere were knitr assigns some object that may take up a lot of memory?
The data set is proprietary and I have tried but failed to make small example where I can reproduce the result. As a note, I do cache some output from some chunks between load_dat and reduce_mem. I use cache.lazy = FALSE to avoid this issue. Here is my sessionInfo
library(knitr)
sessionInfo()
#R R version 3.4.2 (2017-09-28)
#R Platform: x86_64-w64-mingw32/x64 (64-bit)
#R Running under: Windows 7 x64 (build 7601) Service Pack 1
#R
#R Matrix products: default
#R
#R locale:
#R [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
#R [4] LC_NUMERIC=C LC_TIME=English_United States.1252
#R
#R attached base packages:
#R [1] stats graphics grDevices utils datasets methods base
#R
#R other attached packages:
#R [1] knitr_1.17
#R
#R loaded via a namespace (and not attached):
#R [1] compiler_3.4.2 tools_3.4.2 yaml_2.1.16
Regarding question 1.
I also added the following to the log_to_show chunk to figure out if there are objects in other environments in the session that takes up a lot of space
# function to check if `this_env` is in `l`
is_env_in_list <- function(l, this_env){
for(i in l)
if(identical(i, this_env))
return(TRUE)
FALSE
}
# remove duplicates for environments
remove_dup_envs <- function(objs){
do_drop <- logical(length(objs))
for(j in rev(seq_along(objs))){
for(i in seq_len(j - 1L)){
if(identical(objs[[i]], objs[[j]])){
do_drop[j] <- TRUE
break
}
}
}
objs[!do_drop]
}
# attempt to write function to get all unique environments
get_env <- function(this_env = .GlobalEnv, out = NULL, only_new = FALSE){
if(is_env_in_list(out, this_env))
return(if(only_new) NULL else out)
if(identical(this_env, emptyenv()))
return(if(only_new) NULL else out)
new. <- this_env # not emptyenv or in list so we add it
# add parent env
p_env <- parent.env(this_env)
if(!is_env_in_list(out, p_env))
new. <- c(new., get_env(p_env, out, only_new = only_new))
# look through assigned objects, find enviroments and add these
objs <- lapply(ls(envir = this_env), function(x){
o <- try(get(x, envir = this_env), silent = TRUE)
if(inherits(o, "try-error"))
NULL
o
})
objs <- lapply(objs, function(x){
if(is.function(x) && !is.null(environment(x)))
return(environment(x))
x
})
if(length(objs) == 0)
return(if(only_new) new. else remove_dup_envs(c(new., out)))
is_env <- which(sapply(objs, is.environment))
if(length(is_env) == 0)
return(if(only_new) new. else remove_dup_envs(c(new., out)))
objs <- remove_dup_envs(objs[is_env])
keep <- which(!sapply(objs, is_env_in_list, l = c(new., out)))
if(length(keep) == 0L)
return(if(only_new) new. else c(new., out))
objs <- objs[keep]
for(o in objs){
ass_envs <- get_env(o, out = c(new., out), only_new = TRUE)
new. <- c(new., ass_envs)
}
return(if(only_new) new. else remove_dup_envs(c(new., out)))
}
tmp <- get_env(asNamespace("knitr"))
names(tmp) <- sapply(tmp, environmentName)
print(tmp <- tmp[order(names(tmp))])
out <- lapply(tmp, function(x){
o <- sapply(ls(envir = x), function(z){
r <- try(object.size(get(z, envir = x)), silent = TRUE)
if(inherits(r, "try-error"))
return(0)
r
})
if(length(o) == 0L)
return(NULL)
tail(sort(o))
})
max_val <- sapply(out, max)
keep <- which(max_val > 10^7)
out <- out[keep]
max_val <- max_val[keep]
tmp <- tmp[keep]
ord <- order(max_val)
print(tmp <- tmp[ord])
print(out <- out[ord])
It shows no objects that are larger than dat_fit.

Looping through data with Rmd input file with flextable results in pandoc version error - but works fine without the loop?

I'm trying to generate lots of word documents with a loop and RMarkdown. I'm using flextable to make the tables with the acceptable formatting for the report. Everything works fine until I try to loop through a dataset. Then I get an error about the pandoc version:
Error in knit_print.flextable(x, ...) : pandoc
version >= 2.0 required for flextable rendering in docx "
However, It looks like I download version 2.1 on January 19th...
pandoc_version()
[1] ‘1.19.2.1’
Not to mention, it runs fine without the loop when I just run it in the rmd file. (I would think it wouldn't run either way if the version wasn't correct).
I also tried sys.setenv()
Sys.setenv("RSTUDIO_PANDOC" = "PATH TO PANDOC BIN")
But still, it works for the Rmd file alone, but I get the same error about the version when I try to loop it. Again, I feel like this wouldn't work in the rmd file if this wasn't correct.
I'm including a reproducible example below. If I can provide any other information please let me know. Thanks!
My loop/R Script
DAT<-dplyr::sample_n(iris, 10)
Sys.setenv("RSTUDIO_PANDOC" = "PATH TO PANDOC BIN")
for (i in 1:nrow(DAT)){
rmarkdown::render(input = "Loop Testing R Markdown.Rmd",
output_format = "word_document",
output_file = paste("Documents", i, ".docx", sep=''),
output_dir = "Documents/")
}
> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Matrix products: default
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] rmarkdown_1.8 knitr_1.17 bindrcpp_0.2 dplyr_0.7.4
qsurvey_0.0.3 installr_0.19.0
[7] stringr_1.2.0 officer_0.2.1 flextable_0.4.2 pander_0.6.1
kableExtra_0.7.0
loaded via a namespace (and not attached):
[1] zip_1.0.0 Rcpp_0.12.14 bindr_0.1
pillar_1.0.1 compiler_3.4.3
[6] plyr_1.8.4 highr_0.6 R.methodsS3_1.7.1
R.utils_2.6.0 base64enc_0.1-3
[11] tools_3.4.3 digest_0.6.13 uuid_0.1-2 lubridate_1.7.1 jsonlite_1.5
[16] evaluate_0.10.1 tibble_1.4.1 viridisLite_0.2.0 pkgconfig_2.0.1 rlang_0.1.6
[21] shiny_1.0.5 curl_3.1 yaml_2.1.16 httr_1.3.1 xml2_1.1.1
[26] htmlwidgets_0.9 gdtools_0.1.6 hms_0.4.0 DT_0.2 rprojroot_1.3-1
[31] glue_1.2.0 data.table_1.10.4-3 R6_2.2.2 readr_1.1.1 magrittr_1.5
[36] backports_1.1.2 scales_0.5.0 htmltools_0.3.6 assertthat_0.2.0 rvest_0.3.2
[41] xtable_1.8-2 mime_0.5 colorspace_1.3-2 httpuv_1.3.5 stringi_1.1.6
[46] visNetwork_2.0.2 munsell_0.4.3 R.oo_1.21.0
> pandoc_version()
[1] ‘1.19.2.1’
>
The Rmd File to Reference
---
output:
word_document:
reference_docx: mystyles.docx
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r results='asis', include=FALSE}
## Load Packages
library(knitr)
library(rmarkdown)
library(dplyr)
```
```{r results="asis"}
#DAT<-iris # I comment this out when I run the loop, but leave it in when testing the format.
library(pander)
panderOptions('knitr.auto.asis', FALSE)
First_N<-DAT[[i,1]]
Last_N<-DAT[[i,2]]
Name<-c(First_N, " ", Last_N)
Name<-paste(Name, collapse = "")
cat("# ", Name, "\n")
```
## Title of Report Section
```{r, demo1, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
DemoTbl_1<-matrix(nrow = 2, ncol = 4)
DemoTbl_1[[1,1]]<- "Name:"
DemoTbl_1[[1,2]]<- Name
DemoTbl_1[[1,3]]<- "State:"
DemoTbl_1[[1,4]]<-DAT[[i,3]]
DemoTbl_1[[2,1]]<- "Other Feild Title:"
DemoTbl_1[[2,2]]<-DAT[[i,4]]
DemoTbl_1[[2,4]]<-DAT[[i,5]]
DemoTbl_1[[2,3]]<- "Pther Feild Title"
library("flextable")
library("officer")
myft<-regulartable(as.data.frame(DemoTbl_1))
myft <- bg(myft, bg = "#000000", j=1)
myft <- color(myft, color = "#ffffff", j=1)
myft <- border(myft, border = fp_border(color = "#000000"), part = "all")
myft <- align( myft, align = "center", part = "all" )
myft <- width(myft, width = 1.5, j=1)
myft <- width(myft, width = 3, j=2)
myft <- width(myft, width = 1.5, j=3)
myft <- width(myft, width = 1.25, j=4)
myft<- delete_part(myft, part = "header")
myft <- bg(myft, bg = "#000000", j=3)
myft <- color(myft, color = "#ffffff", j=3)
```
```{r, results='asis', echo=FALSE}
#DemoTbl_1 # This prints fine
myft ## This seems to be giving me the error "uitting from lines 77-78
(Loop_Testing_R_Markdown.Rmd) Error in knit_print.flextable(x, ...) : pandoc
version >= 2.0 required for flextable rendering in docx "
```
**Also - In case it's helpful, here is the traceback: **
Error in knit_print.flextable(x, ...) :
pandoc version >= 2.0 required for flextable rendering in docx
20. stop("pandoc version >= 2.0 required for flextable rendering in docx")
19. knit_print.flextable(x, ...)
18. knit_print(x, ...)
17. withVisible(knit_print(x, ...))
16. fun(x, options = options)
15. value_fun(ev$value, ev$visible)
14. withVisible(value_fun(ev$value, ev$visible))
13 .withCallingHandlers(withVisible(value_fun(ev$value, ev$visible)),
warning = wHandler, error = eHandler, message = mHandler)
12. handle(pv <- withCallingHandlers(withVisible(value_fun(ev$value,
ev$visible)), warning = wHandler, error = eHandler, message = mHandler))
11. evaluate_call(expr, parsed$src[[i]], envir = envir, enclos = enclos,
debug = debug, last = i == length(out), use_try = stop_on_error !=
2L, keep_warning = keep_warning, keep_message = keep_message,
output_handler = output_handler, include_timing = include_timing)
10. evaluate(code, envir = env, new_device = FALSE, keep_warning = !isFALSE(options$warning),
keep_message = !isFALSE(options$message), stop_on_error = if (options$error &&
options$include) 0L else 2L, output_handler = knit_handlers(options$render,
options))
9. in_dir(input_dir(), evaluate(code, envir = env, new_device = FALSE,
keep_warning = !isFALSE(options$warning), keep_message = !isFALSE(options$message),
stop_on_error = if (options$error && options$include) 0L else 2L,
output_handler = knit_handlers(options$render, options)))
8. block_exec(params)
7. call_block(x)
6. process_group.block(group)
5. process_group(group)
4. withCallingHandlers(if (tangle) process_tangle(group) else process_group(group),
error = function(e) {
setwd(wd)
cat(res, sep = "\n", file = output %n% "") ...
3. process_file(text, output)
2. knitr::knit(knit_input, knit_output, envir = envir, quiet = quiet,
encoding = encoding)
1. rmarkdown::render(input = "Loop Testing R Markdown.Rmd", output_format = "word_document",
output_file = paste("Documents", i, ".docx", sep = ""), output_dir = "Documents/")
You need to create a file .Rprofile at the root of your R project (see ?Startup). In that file add your R instruction to set pandoc path (Sys.setenv("RSTUDIO_PANDOC" = "PATH TO PANDOC BIN")).
rmarkdown::render is using a new R session and your variable is not set when rendering.

Error handling within Sexpr

How do I permit errors within \Sexpr?
I have a knitr document. A small part of this document refers to a file that cannot be shared. So whenever \Sexpr{a} is called on for some object a that depends on that file being read, it returns an error. I'd like instead for \Sexpr to print that it encountered an error.
For example,
\documentclass{article}
\usepackage{xcolor} % for red
\begin{document}
<<>>=
x <- 1
#
The value of $x$ is \Sexpr{x}
<<>>=
a <- scan("secret_file.txt")
#
The value of $a$ is \Sexpr{a}.
\end{document}
will not compile (when secret_file.txt isn't present). I'd like the output to look something like:
I thought that altering the inline hook would work, but putting the following chunk made no difference.
<<Sexpr-setup>>=
library(knitr)
knit_hooks$set(inline = function(x){
out <- tryCatch(
{
if (is.numeric(x))
x = round(x, getOption("digits"))
paste(as.character(x), collapse = ", ")
},
error = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr error!}}")
invisible(NULL)
},
warning = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr warning!}}")
invisible(NULL)
}
)
return(out)
})
#
It is not essential to have a custom error message, only that errors are clear from the output and do not prevent compilation. I appreciate that I could do a find replace into something like \Sexpr{XX( and define a function upfront XX() that does the same tryCatch maneouvre, but I thought knitr could do this.
Calling knitr::knit on the above and applying the traceback shows that:
11: eval(expr, envir, enclos)
10: eval(parse_only(code[i]), envir = envir)
9: withVisible(eval(parse_only(code[i]), envir = envir))
8: inline_exec(block)
7: in_dir(opts_knit$get("root.dir") %n% input_dir(), inline_exec(block))
6: call_inline(x)
5: process_group.inline(group)
4: process_group(group)
3: withCallingHandlers(if (tangle) process_tangle(group) else process_group(group),
error = function(e) {
setwd(wd)
cat(res, sep = "\n", file = output %n% "")
message("Quitting from lines ", paste(current_lines(i),
collapse = "-"), " (", knit_concord$get("infile"),
") ")
})
2: process_file(text, output)
1: knitr::knit("knitr-prevent-errors.Rnw", quiet = TRUE)
From following the functions, it appears that the error is low down at
eval(parse_only(code[i]), envir = envir)
Where code[i] is a. Am I right in thinking that the only way to resolve this is to change the line starting v = with a tryCatch?
With the option include=FALSE in the setup chunk,the following worked for me with output as below. If it does not work for you I will delete the post
\documentclass{article}
\usepackage{xcolor} % for red
<<setup, include=FALSE>>=
knit_hooks$set(inline = function(x) {
out <- tryCatch(
{
if (is.numeric(x))
x = round(x, getOption("digits"))
paste(as.character(x), collapse = ", ")
},
error = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr error!}}")
invisible(NULL)
},
warning = function(cond){
return("\\textcolor{red}{\\textbf{Sexpr warning!}}")
invisible(NULL)
}
)
return(out)
})
#
\begin{document}
<<>>=
x <- 1
#
The value of $x$ is \Sexpr{x}
<<>>=
a <- scan("secret_file.txt")
#
The value of $a$ is \Sexpr{a}.
\end{document}
Knitr Output:
>knitr::knit("test.Rnw")
processing file: test.Rnw
|......... | 14%
ordinary text without R code
|................... | 29%
label: setup (with options)
List of 2
$ include: logi FALSE
$ indent : chr " "
|............................ | 43%
ordinary text without R code
|..................................... | 57%
label: unnamed-chunk-1 (with options)
List of 1
$ indent: chr " "
|.............................................. | 71%
inline R code fragments
|........................................................ | 86%
label: unnamed-chunk-2 (with options)
List of 1
$ indent: chr " "
|.................................................................| 100%
inline R code fragments
output file: test.tex
[1] "test.tex"
Tex Output:
>texi2pdf("test.tex")
>
I am using MikTex 2.9,knitr 1.9, R 3.0.2 on Windows , can you please attach your log files then we can compare the differences if any

Getting example codes of R functions into knitr using helpExtract function

I want to get the example codes of R functions to use in knitr. There might be an easy way but tried the following code using helpExtract function which can be obtained from here (written by #AnandaMahto). With my approach I have to look whether a function has Examples or not and have to include only those functions which have Examples.
This is very inefficient and naive approach. Now I'm trying to include only those functions which have Examples. I tried the following code but it is not working as desired. How can I to extract Examples codes from an R package?
\documentclass{book}
\usepackage[T1]{fontenc}
\begin{document}
<< label=packages, echo=FALSE>>=
library(ggplot2)
library(devtools)
source_gist("https://gist.github.com/mrdwab/7586769")
library(noamtools) # install_github("noamtools", "noamross")
#
\chapter{Linear Model}
<< label = NewTest1, results="asis">>=
tryCatch(
{helpExtract(lm, section="Examples", type = "s_text");
cat(
"\\Sexpr{
knit_child(
textConnection(helpExtract(lm, section=\"Examples\", type = \"s_text\"))
, options = list(tidy = FALSE, eval = TRUE)
)
}", "\n"
)
}
, error=function(e) FALSE
)
#
\chapter{Modify properties of an element in a theme object}
<< label = NewTest2, results="asis">>=
tryCatch(
{helpExtract(add_theme , section="Examples", type = "s_text");
cat(
"\\Sexpr{
knit_child(
textConnection(helpExtract(add_theme , section=\"Examples\", type = \"s_text\"))
, options = list(tidy = FALSE, eval = TRUE)
)
}", "\n"
)
}
, error=function(e) FALSE
)
#
\end{document}
I've done some quick work modifying the function (which I've included at this Gist). The Gist also includes a sample Rnw file (I haven't had a chance to check an Rmd file yet).
The function now looks like this:
helpExtract <- function(Function, section = "Usage", type = "m_code", sectionHead = NULL) {
A <- deparse(substitute(Function))
x <- capture.output(tools:::Rd2txt(utils:::.getHelpFile(utils::help(A)),
options = list(sectionIndent = 0)))
B <- grep("^_", x) ## section start lines
x <- gsub("_\b", "", x, fixed = TRUE) ## remove "_\b"
X <- rep(FALSE, length(x)) ## Create a FALSE vector
X[B] <- 1 ## Initialize
out <- split(x, cumsum(X)) ## Create a list of sections
sectionID <- vapply(out, function(x) ## Identify where the section starts
grepl(section, x[1], fixed = TRUE), logical(1L))
if (!any(sectionID)) { ## If the section is missing...
"" ## ... just return an empty character
} else { ## Else, get that list item
out <- out[[which(sectionID)]][-c(1, 2)]
while(TRUE) { ## Remove the extra empty lines
out <- out[-length(out)] ## from the end of the file
if (out[length(out)] != "") { break }
}
switch( ## Determine the output type
type,
m_code = {
before <- "```r"
after <- "```"
c(sectionHead, before, out, after)
},
s_code = {
before <- "<<eval = FALSE>>="
after <- "#"
c(sectionHead, before, out, after)
},
m_text = {
c(sectionHead, paste(" ", out, collapse = "\n"))
},
s_text = {
before <- "\\begin{verbatim}"
after <- "\\end{verbatim}"
c(sectionHead, before, out, after)
},
stop("`type` must be either `m_code`, `s_code`, `m_text`, or `s_text`")
)
}
}
What has changed?
A new argument sectionHead has been added. This is used to be able to specify the section title in the call to the helpExtract function.
The function checks to see whether the relevant section is available in the parsed document. If it is not, it simply returns a "" (which doesn't get printed).
Example use would be:
<<echo = FALSE>>=
mySectionHeading <- "\\section{Some cool section title}"
#
\Sexpr{knit_child(textConnection(
helpExtract(cor, section = "Examples", type = "s_code",
sectionHead = mySectionHeading)),
options = list(tidy = FALSE, eval = FALSE))}
Note: Since Sexpr doesn't allow curly brackets to be used ({), we need to specify the title outside of the Sexpr step, which I have done in a hidden code chunk.
This is not a complete answer so I'm marking it as community wiki. Here are two simple lines to get the examples out of the Rd file for a named function (in this case lm). The code is much simpler than Ananda's gist in my opinion:
x <- utils:::.getHelpFile(utils::help(lm))
sapply(x[sapply(x, function(z) attr(z, "Rd_tag") == "\\examples")][[1]], `[[`, 1)
The result is a simple vector of all of the text in the Rd "examples" section, which should be easy to parse, evaluate, or include in a knitr doc.
[1] "\n"
[2] "require(graphics)\n"
[3] "\n"
[4] "## Annette Dobson (1990) \"An Introduction to Generalized Linear Models\".\n"
[5] "## Page 9: Plant Weight Data.\n"
[6] "ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)\n"
[7] "trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)\n"
[8] "group <- gl(2, 10, 20, labels = c(\"Ctl\",\"Trt\"))\n"
[9] "weight <- c(ctl, trt)\n"
[10] "lm.D9 <- lm(weight ~ group)\n"
[11] "lm.D90 <- lm(weight ~ group - 1) # omitting intercept\n"
[12] "\n"
[13] "\n"
[14] "opar <- par(mfrow = c(2,2), oma = c(0, 0, 1.1, 0))\n"
[15] "plot(lm.D9, las = 1) # Residuals, Fitted, ...\n"
[16] "par(opar)\n"
[17] "\n"
[18] "\n"
[19] "### less simple examples in \"See Also\" above\n"
Perhaps the following might be useful.
get.examples <- function(pkg=NULL) {
suppressWarnings(f <- unique(utils:::index.search(TRUE, find.package(pkg))))
out <- setNames(sapply(f, function(x) {
tf <- tempfile("Rex")
tools::Rd2ex(utils:::.getHelpFile(x), tf)
if (!file.exists(tf)) return(invisible())
readLines(tf)
}), basename(f))
out[!sapply(out, is.null)]
}
ex.base <- get.examples('base')
This returns the examples for all functions (that have documentation containing examples) within the specified vector of packages. If pkg=NULL, it returns the examples for all functions within loaded packages.
For example:
ex.base['scan']
# $scan
# [1] "### Name: scan"
# [2] "### Title: Read Data Values"
# [3] "### Aliases: scan"
# [4] "### Keywords: file connection"
# [5] ""
# [6] "### ** Examples"
# [7] ""
# [8] "cat(\"TITLE extra line\", \"2 3 5 7\", \"11 13 17\", file = \"ex.data\", sep = \"\\n\")"
# [9] "pp <- scan(\"ex.data\", skip = 1, quiet = TRUE)"
# [10] "scan(\"ex.data\", skip = 1)"
# [11] "scan(\"ex.data\", skip = 1, nlines = 1) # only 1 line after the skipped one"
# [12] "scan(\"ex.data\", what = list(\"\",\"\",\"\")) # flush is F -> read \"7\""
# [13] "scan(\"ex.data\", what = list(\"\",\"\",\"\"), flush = TRUE)"
# [14] "unlink(\"ex.data\") # tidy up"
# [15] ""
# [16] "## \"inline\" usage"
# [17] "scan(text = \"1 2 3\")"
# [18] ""
# [19] ""
# [20] ""
# [21] ""

R markdown presentation not displaying plots

I have Rstudio on Windows (sessionInfo() below) and am trying to build an r presentation using markdown. When I try to knit HTML or PDF it does not seem to be retaining the folder where plots should be generated from and as a result my presentations are missing plots. I have confirmed that it does work with a basic html_document though.
Does anyone have any ideas on how to resolve?
MWE (rstudio default with headers for slides)
---
title: "plottest2"
author: "AN Other"
date: "Monday, June 30, 2014"
output: html_document
---
## Area 1 ##
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}
summary(cars)
```
## Area 2 ##
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
This generates using the knit html command, but change html_document to ioslides_presentation and it won't pick up the plot
SessionInfo
> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=English_United Kingdom.1252 LC_CTYPE=English_United Kingdom.1252 LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] lattice_0.20-29 ggplot2_1.0.0
loaded via a namespace (and not attached):
[1] colorspace_1.2-4 digest_0.6.4 evaluate_0.5.5 formatR_0.10 grid_3.1.0 gtable_0.1.2 htmltools_0.2.4 knitr_1.6 labeling_0.2 MASS_7.3-31
[11] munsell_0.4.2 plyr_1.8.1 proto_0.3-10 Rcpp_0.11.2 reshape2_1.4 rmarkdown_0.2.49 scales_0.2.4 stringr_0.6.2 tools_3.1.0 yaml_2.1.13
C:\Program Files\R\R-3.1.0\library\base\R.Rprofile
### This is the system Rprofile file. It is always run on startup.
### Additional commands can be placed in site or user Rprofile files
#
# Copyright (C) 1995-2012 The R Core Team
### (see ?Rprofile).
### Notice that it is a bad idea to use this file as a template for
### personal startup files, since things will be executed twice and in
### the wrong environment (user profiles are run in .GlobalEnv).
.GlobalEnv <- globalenv()
attach(NULL, name = "Autoloads")
.AutoloadEnv <- as.environment(2)
assign(".Autoloaded", NULL, envir = .AutoloadEnv)
T <- TRUE
F <- FALSE
R.version <- structure(R.Version(), class = "simple.list")
version <- R.version # for S compatibility
## for backwards compatibility only
R.version.string <- R.version$version.string
## NOTA BENE: options() for non-base package functionality are in places like
## --------- ../utils/R/zzz.R
options(keep.source = interactive())
options(warn = 0)
# options(repos = c(CRAN="#CRAN#"))
# options(BIOC = "http://www.bioconductor.org")
options(timeout = 60)
options(encoding = "native.enc")
options(show.error.messages = TRUE)
## keep in sync with PrintDefaults() in ../../main/print.c :
options(scipen = 0)
options(max.print = 99999)# max. #{entries} in internal printMatrix()
options(add.smooth = TRUE)# currently only used in 'plot.lm'
options(stringsAsFactors = TRUE)
if(!interactive() && is.null(getOption("showErrorCalls")))
options(showErrorCalls = TRUE)
local({dp <- Sys.getenv("R_DEFAULT_PACKAGES")
if(identical(dp, "")) # marginally faster to do methods last
dp <- c("datasets", "utils", "grDevices", "graphics",
"stats", "methods")
else if(identical(dp, "NULL")) dp <- character(0)
else dp <- strsplit(dp, ",")[[1]]
dp <- sub("[[:blank:]]*([[:alnum:]]+)", "\\1", dp) # strip whitespace
options(defaultPackages = dp)
})
## Expand R_LIBS_* environment variables.
Sys.setenv(R_LIBS_SITE =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_SITE")))
Sys.setenv(R_LIBS_USER =
.expand_R_libs_env_var(Sys.getenv("R_LIBS_USER")))
.First.sys <- function()
{
for(pkg in getOption("defaultPackages")) {
res <- require(pkg, quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE)
if(!res)
warning(gettextf('package %s in options("defaultPackages") was not found', sQuote(pkg)),
call.=FALSE, domain = NA)
}
}
.OptRequireMethods <- function()
{
if("methods" %in% getOption("defaultPackages")) {
res <- require("methods", quietly = TRUE, warn.conflicts = FALSE,
character.only = TRUE)
if(!res)
warning('package "methods" in options("defaultPackages") was not found', call.=FALSE)
}
}
if(nzchar(Sys.getenv("R_BATCH"))) {
.Last.sys <- function()
{
cat("> proc.time()\n")
print(proc.time())
}
## avoid passing on to spawned R processes
## A system has been reported without Sys.unsetenv, so try this
try(Sys.setenv(R_BATCH=""))
}
###-*- R -*-
## this will break if R is on a network share
.Library <- file.path(chartr("\\", "/", R.home()), "library")
.Library.site <- Sys.getenv("R_LIBS_SITE")
.Library.site <- if(!nchar(.Library.site)) file.path(R.home(), "site-library") else unlist(strsplit(.Library.site, ";"))
.Library.site <- .Library.site[file.exists(.Library.site)]
if(!nzchar(Sys.getenv("R_LIBS_USER")))
Sys.setenv(R_LIBS_USER=
file.path(Sys.getenv("R_USER"), "R",
"win-library",
paste(R.version$major,
sub("\\..*$", "", R.version$minor),
sep=".")
))
invisible(.libPaths(c(unlist(strsplit(Sys.getenv("R_LIBS"), ";")),
unlist(strsplit(Sys.getenv("R_LIBS_USER"), ";"))
)))
local({
popath <- Sys.getenv("R_TRANSLATIONS", "")
if(!nzchar(popath)) {
paths <- file.path(.libPaths(), "translations", "DESCRIPTION")
popath <- dirname(paths[file.exists(paths)][1])
}
bindtextdomain("R", popath)
bindtextdomain("R-base", popath)
bindtextdomain("RGui", popath)
assign(".popath", popath, .BaseNamespaceEnv)
})
if(nzchar(Sys.getenv("R_PAPERSIZE"))) {
options(papersize = Sys.getenv("R_PAPERSIZE"))
} else {
if(grepl("(canada|united.states)", Sys.getlocale("LC_MONETARY"),
ignore.case = TRUE)) options(papersize = "letter")
else options(papersize = "a4")
}
options(pager = if(length(grep("--ess", commandArgs()))) "console" else "internal",
useFancyQuotes = (.Platform$GUI == "Rgui"),
pdfviewer = Sys.getenv("R_PDFVIEWER", file.path(R.home("bin"), "open.exe")))
if(.Platform$GUI == "Rgui")
Sys.setenv(GFORTRAN_STDOUT_UNIT = "-1", GFORTRAN_STDERR_UNIT = "-1")
local({
br <- Sys.getenv("R_BROWSER", NA_character_)
if(!is.na(br)) options(browser = br)
tests_startup <- Sys.getenv("R_TESTS")
if(nzchar(tests_startup)) source(tests_startup)
})
C:\Program Files\R\R-3.1.0\etc\Rprofile.site
# Things you might want to change
# options(papersize="a4")
# options(editor="notepad")
# options(pager="internal")
# set the default help type
# options(help_type="text")
options(help_type="html")
# set a site library
# .Library.site <- file.path(chartr("\\", "/", R.home()), "site-library")
# set a CRAN mirror
# local({r <- getOption("repos")
# r["CRAN"] <- "http://my.local.cran"
# options(repos=r)})
# Give a fortune cookie, but only to interactive sessions
# (This would need the fortunes package to be installed.)
# if (interactive())
# fortunes::fortune()
I have found the same issue with RStudio-0.98.983 and R-3.1.1-win. Uninstalling both and reinstalling did NOT solve the issue for me. I have tried with RStudio-0.98.994 and it did not work either...
Update: This was reported (see link in the comments below) and a solution was found by the RStudio team. It seems it is an issue with the Lua base64 encoder on Windows, which is used in ioslides. The solution is to install the packages httpuv or catools. After restarting RStudio, the issue should be fixed (at least it was for me!).
I had a similar problem with a chart not being displayed. It turned out that the problem was that the name of the .Rpres file I was using had spaces in it. Once I replaced the spaces with underscores the plot appeared again.
Use "Example_File_Name.Rpres" not "Example File Name.Rpres".
I had the same problem, and a different solution worked for me.
- don't save the rmarkdown with any numbers in the document name,
- and also don't inlcude the .html in the document name, to the markdown file you wish to save
Using just a name without the two above should create one rmd-file and one html-file in your designated folder. The rmd-file will not include plots, the html-File however should inlcude them in its presentation.
This is a localised issue - an install on a fresh computer did not have this error. It could be due to having previous versions of R hanging around - suggest taking the route of completely uninstalling R and Rstudio.
Uninstalling R and Rstudio works.

Resources