R markdown presentation not displaying plots - r

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.

Related

Compile quarto document in temporary directory in 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)

knitr bookdown::gitbook and webgl: rotation does not work properly

I have the following Rmd file:
---
output: bookdown::gitbook
---
```{r include=FALSE}
rgl::setupKnitr()
```
```{r testing1,webgl=TRUE}
with(attitude,
car::scatter3d(x = rating, z = complaints, y = learning)
)
```
```{r testing2,webgl=TRUE}
with(attitude,
car::scatter3d(x = rating, z = complaints, y = learning)
)
```
When I knit this file, it produces and HTML file containing two, identical 3D interactive scatterplots. Both scatterplots look like they should, but the second scatterplot does not rotate properly. It will not rotate horizontally in depth correctly (eg, around the vertical axis).
In case it helps, you can find the HTML output of the knit here: https://www.dropbox.com/s/v3usmtes7n54t6q/Untitled.html.zip?dl=0
I have done all the following, none of which have fixed the problem:
Updated all packages with update.packages().
Installed the development version of bookdown.
Installed the development version of knitr.
Tried the solution here (didn't work): interactive 3D plots in markdown file - not working anymore?
I have noted the following:
If I change the output to html_document I do not have the problem (I'm debugging the problem in a bookdown::gitbook though, so that knowledge does not directly help me).
In the Firefox (77.0.1, 64-bit) javascript error console there is an error: TypeError: li[0] is undefined / plugin-bookdown.js:152:43 (which appears to have something to do with the table of contents and scrolling?)
Here is the output of sessionInfo():
> sessionInfo()
R version 4.0.0 (2020-04-24)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Catalina 10.15.5
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
loaded via a namespace (and not attached):
[1] bookdown_0.19.4 fansi_0.4.1 digest_0.6.25 crayon_1.3.4
[5] assertthat_0.2.1 evaluate_0.14 rlang_0.4.6 cli_2.0.2
[9] rstudioapi_0.11 rmarkdown_2.3 tools_4.0.0 glue_1.4.1
[13] xfun_0.14 yaml_2.2.1 rsconnect_0.8.16 compiler_4.0.0
[17] htmltools_0.5.0 knitr_1.28.7
In addition, here are the versions of some other relevant packages:
> installed.packages()[c("rgl","mgcv","car"),"Version"]
rgl mgcv car
"0.100.54" "1.8-31" "3.0-8"
Edit to add more detail
I have the same problem while using rgl::persp3d, so it isn't specific to car::scatter3d. The HTML from the Rmd file below uses only rgl but exhibits the same behavior.
---
output: bookdown::gitbook
---
```{r include=FALSE}
rgl::setupKnitr()
x <- seq(-10, 10, length = 30)
y <- x
f <- function(x, y) { r <- sqrt(x^2 + y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
```
```{r testing1,webgl=TRUE}
rgl::persp3d(x, y, z, aspect = c(1, 1, 0.5), col = "lightblue",
xlab = "X", ylab = "Y", zlab = "Sinc( r )",
polygon_offset = 1)
```
```{r testing2,webgl=TRUE}
rgl::persp3d(x, y, z, aspect = c(1, 1, 0.5), col = "lightblue",
xlab = "X", ylab = "Y", zlab = "Sinc( r )",
polygon_offset = 1)
```
This turned out to be a bug in rgl, that was using an obsolete method to compute the location of mouse clicks relative to objects in scenes. It worked in an html_document, but not with bookdown::gitbook.
The development version (0.102.6) of rgl has fixed this, but it contains some really major changes, and a few other things are still broken by them: in particular using the webgl=TRUE chunk option. If you want to use the devel version, you should use explicit calls to rglwidget() in each chunk, or if you want to try out the new stuff, use rgl::setupKnitr(autoprint = TRUE) and just treat rgl graphics like base graphics, controlled by chunk options fig.keep etc.
Edited to add: version 0.102.7 fixes the known webgl=TRUE issue.

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.

specifying output path for knit2html

I'm having trouble specifying an output path for the html generated by knit2html or its dependent functions. I would like to specify 'outfile' in the the call to knit2html(), but I get the error,
Error in knit2html(input = "test.Rmd", output = "test-abcd.html") :
object 'outfile' not found
'output' is a parameter of markdownToHTML which should work I'd think. I can't find anywhere in the source where 'outfile' is used.
This should reproduce my experience.
library(knitr)
library(markdown)
# a minimal example
writeLines(c("```{r hello-random, echo=TRUE}", "rnorm(5)", "```"),
"test.Rmd")
# this works and outputs to test.html
knit2html(input = "test.Rmd")
# this generates the above error
knit2html(input = "test.Rmd",
output = "test-abcd.html")
# breaking it down into two steps works in this simple case,
# but not in my application. trying to diagnose that difference currently
knit("test.Rmd")
markdownToHTML("test.md",
output="test-abcd.html")
relevant version info might be useful?
sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: x86_64-pc-linux-gnu (64-bit)
other attached packages:
[1] plyr_1.8 knitr_1.2 digest_0.6.3 markdown_0.5.4 xtable_1.7-1 reshape2_1.2.2 scales_0.2.3 ggplot2_0.9.3.1 data.table_1.8.8
First, thanks for the very clear and reproducible question. If you take a look at the knit2html function source code, you can understand what the problem is :
R> knit2html
function (input, ..., envir = parent.frame(), text = NULL, quiet = FALSE,
encoding = getOption("encoding"))
{
if (is.null(text)) {
out = knit(input, envir = envir, encoding = encoding,
quiet = quiet)
markdown::markdownToHTML(out, outfile <- sub_ext(out,
"html"), ...)
invisible(outfile)
}
else {
out = knit(text = text, envir = envir, encoding = encoding,
quiet = quiet)
markdown::markdownToHTML(text = out, ...)
}
}
<environment: namespace:knitr>
If the text argument is NULL (ie, if you provide a file as input instead of a character vector), then the given file is passed to the knit function, and the markdownToHTML function is called the following way :
markdown::markdownToHTML(out, outfile <- sub_ext(out, "html"), ...)
So in this case the output file name is generated by substituting the existing file name extension with html, and you can't provide your own output filename as an argument.

Resources