Rstudio pandoc issue - r

This example will knit on my laptop but not my desktop. Both are using the same RStudio and R versions. I have tried uninstalling R and RStudio, changing R and RStudio versions, changing 32/64 bit R, trying to install a variety of pandoc versions, setting the path to pandoc manually with Sys.setenv()... I am sort of at a loss here.
Both machines have the following:
> rmarkdown::pandoc_version()
[1] ‘1.19.2.1’
> version
_
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 4.3
year 2017
month 11
day 30
svn rev 73796
language R
version.string R version 3.4.3 (2017-11-30)
nickname Kite-Eating Tree
Here is a minimum non/working example. Again, it works on the laptop but not the desktop.
---
title: "Pandoc testing sandbox"
output:
html_document:
df_print: paged
number_sections: yes
toc: yes
toc_float:
collapsed: no
smooth_scroll: no
---
Here is a chunk of code to test:
```{r, results = "asis", echo = FALSE, message = FALSE}
tex2markdown <- function(texstring) {
writeLines(text = texstring,
con = myfile <- tempfile(fileext = ".tex"))
texfile <- knitr::pandoc(input = myfile, format = "html")
cat(readLines(texfile), sep = "\n")
unlink(c(myfile, texfile))
}
textable <- "
\\begin{table}[]
\\centering
\\begin{tabular}{l | c | c}
& without replacement & with replacement \\\\ \\hline
order matters & permutation: $\\frac{n!}{(n-k)!}$ & $n^k$ \\\\ \\hline
order does not matter & combination: ${n\\choose k}=\\frac{n!}{k!(n-k)!}$ & (\\textit{special case}) \\hline
\\end{tabular}
\\end{table}
"
tex2markdown(textable)
```
The error text on the desktop machine is:
Line 17 Error in knitr::pandoc(input = myfile, format = "html") :
Please install pandoc first: http://pandoc.org
Calls: <Anonymous> ... withVisible -> eval -> eval ->
tex2markdown -> <Anonymous> Execution halted
Any help with this would be greatly appreciated!
===
Edit: I did a bit more testing and ran:
rmarkdown::render("pandoctest.Rmd", "html_document")
And there was an option to "Rerun with Debug", so I did that, and the error is happening in "Function pandoc (namespace:knitr)" The line of code where the break happens in what I suppose is the pandoc function in the knitr package is:
...
if (Sys.which("pandoc") == "")
stop("Please install pandoc first: http://pandoc.org")
...
So it seems like pandoc is checking to see if it is installed itself? Or somehoe this is a pandoc function in the knitr package that is calling an actual pandoc program from somewhere else? SO it seems I need to get knitr to somehow see that I have pandoc installed.

Related

create PDF with preamble from rmarkdown::render

I am trying to create a PDF from R. I am successful from within RStudio (choosing "Knit to PDF"), but I get an error invoking from R (either with ctl-enter in Rstudio or with Rscript --vanilla invoke_from_R.R from the command line). My actual need is to create from the command line.
For example:
invoke_from_R.Rmd
---
title: "Lumber Jacks"
author: "Washington Irving"
date: "2022-09-19"
output:
pdf_document:
keep_tex: true
keep_md: true
dev: pdf
includes:
in_header: invoke_from_R_preamble.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Where are we?
Dove siamo?
invoke_from_R_preamble.tex
\newcommand\T{\rule{0pt}{2.6ex}} % Top strut
\newcommand\B{\rule[-1.2ex]{0pt}{0pt}} % Bottom strut
invoke_from_R.R
rmarkdown::render(
input = "invoke_from_R.Rmd"
, output_file = "invoke_from_R.pdf"
, output_format = rmarkdown::pdf_document(
rmarkdown::includes(in_header = "invoke_from_R_preamble.tex"),
toc = TRUE
, toc_depth = 2
, number_sections = FALSE
, keep_md = TRUE
, keep_tex = TRUE
, fig_width = 6.5
, fig_height = 4.5
, fig_crop = FALSE
)
)
The error that I get is:
$ Rscript --vanilla invoke_from_R.R
Error in !implicit_figures : invalid argument type
Calls: <Anonymous> ... <Anonymous> -> output_format -> pandoc_options -> from_rmarkdown
Execution halted
I have not yet found a workaround.
When I comment out this line:
rmarkdown::includes(in_header = "invoke_from_R_preamble.tex"),
I don't get the error, but I need to use the preamble because some of my LaTeX macros get processed even when I use the setting that is supposed to prevent this.
I am using (on Linux):
R version 4.2.1 (2022-06-23)
rmarkdown 2.14
Suggestions?
Thank you.

Execute multiline R expression from shell (with indentation)

I'm trying to achieve what you might naively write as:
R -e "
rmarkdown::render(
'MyDocument.Rmd',
params = list(
year = 2017
),
output_file = 'ExampleRnotebook.html'
)
"
So that I can make nicely formatted submission scripts to run on a cluster.
I've tried some variants on the below, I'm wondering if there might be an alternative approach to do this with the R -f flag?
read -r -d '' EXP << EOF
rmarkdown::render(
'MyDocument.Rmd',
params = list(
year = 2017
),
output_file = 'ExampleRnotebook.html'
)
EOF
R -e "$EXP"
but I get a series of errors that look like this:
ARGUMENT 'params~+~=~+~list(' __ignored__
for the different lines of the expression, followed by:
> rmarkdown::render(
+
+ Error: unexpected end of input
To reproduce:
MyDocument.Rmd =
---
title: "R Notebook"
output: html_notebook
params:
year: 0000
---
```{r}
params$year
```
This works fine:
read -r -d '' EXP <<- EOF
rmarkdown::render('MyDocument.Rmd', params = list(year = 2017 ), output_file = 'ExampleRnotebook.html')
EOF
R -e "$EXP"
but gets hard to read with longer param lists
This works for me (R version 3.5.0):
R --no-save <<code
for(i in 1:3) {
i +
2
}
print(i)
runif(5,
1,10)
code
Note: line-breaks and paddings are intentional.

Stargazer splits character field into columns when summary=F and string contains "&"

How can I print a stargazer table when summary=F and a character column has elements containing &? summary=F prints the data table verbatim which is what I want.
Here's a case where it prints as expected:
> stargazer::stargazer(
+ data.frame(ur1=c('hot','tamale'),yum='!')
+ ,type='text',summary=F)
============
ur1 yum
------------
1 hot !
2 tamale !
------------
And here the & is split into two columns.
> stargazer::stargazer(
+ data.frame(ur1=c('hot & tamale'),yum='!')
+ ,type='text',summary=F)
============
ur1 yum
------------
1 hot tamale
------------
The same behavior happens in html and latex modes as well. In latex it's easy to hack a fix for a character by commenting out the & a la gsub(x,pattern='&',replacement='\\&',fixed=T) but that fix doesn't work for html and replacing it with the entity & still causes the split. While it would be easy to use kable or simple markdown to print the table, I want my this kind of table to have the same style as the stargazer regression tables.
I hope someone can help! Also, I couldn't find a development repo to report it if it's a bug.
I do have the latest version of stargazer:
> devtools::session_info()
Session info ------------------
setting value
version R version 3.4.4 (2018-03-15)
system x86_64, linux-gnu
ui RStudio (1.1.419)
language (EN)
collate en_US.UTF-8
tz Etc/UTC
date 2018-09-14
Packages ----------------------
stargazer 5.2.2 2018-05-30 CRAN (R 3.4.4)
It's a very hacky solution, but you could insert a tab (\t) and a backspace (\b) escape sequence right before the &. This seems to work for type = "text" and type = "html", but not type = "latex".
dat <- data.frame(ur1=c('hot & tamale', 'hot & taco') ,yum='!')
dat[, 1] <- gsub("&", "\t\b&", dat[, 1])
stargazer::stargazer(dat, type = "text", summary=F)
====================
ur1 yum
--------------------
1 hot & tamale !
2 hot & taco !
--------------------

R optparse error with command line arguments

For some reason, the optparse usage in this script breaks:
test.R:
#!/usr/bin/env Rscript
library("optparse")
option_list <- list(
make_option(c("-n", "--name"), type="character", default=FALSE,
dest="report_name", help="A different name to use for the file"),
make_option(c("-h", "--height"), type="numeric", default=12,
dest = "plot_height", help="Height for plot [default %default]",
metavar="plot_height"),
make_option(c("-w", "--width"), type="numeric", default=10,
dest = "plot_width", help="Width for plot [default %default]",
metavar="plot_width")
)
opt <- parse_args(OptionParser(option_list=option_list), positional_arguments = TRUE)
print(opt)
report_name <- opt$options$report_name
plot_height <- opt$options$plot_height
plot_width <- opt$options$plot_width
input_dir <- opt$args[1] # input directory
I get this error:
$ ./test.R --name "report1" --height 42 --width 12 foo
Error in getopt(spec = spec, opt = args) :
redundant short names for flags (column 2).
Calls: parse_args -> getopt
Execution halted
However, if I remove the "-h" from this line:
make_option(c("--height"), type="numeric", default=12,
dest = "plot_height", help="Height for plot [default %default]"
It seems to work fine;
$ ./test.R --name "report1" --height 42 --width 12 foo
$options
$options$report_name
[1] "report1"
$options$plot_height
[1] 42
$options$plot_width
[1] 12
$options$help
[1] FALSE
$args
[1] "foo"
Any ideas what might be going on here?
I am using R 3.3.0 and optparse_1.3.2 (getopt_1.20.0)
The -h flag is reserved by optparse (which is described as a feature of optparse which is not in getopt, from the getopt.R source file on Github):
Some features implemented in optparse package unavailable in getopt:
2. Automatic generation of an help option and printing of help text when encounters an "-h"
Therefore, when the user specifies -h, the sanity check for uniqueness of flags fails. The issue tracker does not seem to have any mention of the need to create a better error message for this case, however.
Finally, note that optparse seems to be invoking getopt, as they have the same author.

R > Monetdb, dbConnect error (package Monetdb.R)

I'm getting an error when trying to connect (dbConnect()) from within R to MonetDB (using MonetDB.R). There is a (related SO question) and I also tryed the sugestions there ( (a) use MonetDB.R beta version 0.9.5 or (a) use the regular MonetDB.R but replace DBI package with an earlier version (0.2-7)) without success.
This is the code and errors:
library(MonetDB.R)
options( "monetdb.sequential" = TRUE )
setwd("C:/Users/lucas_000/Desktop/Curso R/importa_RAIS")
batfile <-
monetdb.server.setup(
database.directory = paste( getwd() , "/MonetDB", sep="") ,
monetdb.program.path =
ifelse(.Platform$OS.type == "windows" , "C:/Program Files/MonetDB/MonetDB5" , "" ) ,
dbname = "RAIS" , dbport = 50003
)
batfile <- "C:/Users/lucas_000/Desktop/Curso R/importa_RAIS/MonetDB/RAIS.bat"
dbname <- "RAIS"
dbport <- 50003
pid <- as.numeric(monetdb.server.start( batfile ))
# output indicates: MonetDB 5 server v11.17.21 "Jan2014-SP3"
db <- dbConnect( MonetDB.R() , "monetdb://localhost:5003/RAIS" , wait = TRUE )
Assertion Failed!
Program: C\:Program Files\RStudio\bin\x64\rsession.exe
File: mapi.c, Line 91
Expression: IS_INTEGER(port)
#Then RStudio displays an error: "R Session Aborted"
Sistem details:
Windows 8.0, on RStudio, Version 0.98.1062
> sessionInfo()
R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
other attached packages:
[1] R.utils_1.33.0 R.oo_1.18.0 R.methodsS3_1.6.1 downloader_0.3
[5] RCurl_1.95-4.3 bitops_1.0-6 sqlsurvey_0.6-11 survey_3.30-3
[9] KernSmooth_2.23-12 MonetDB.R_0.9.4 digest_0.6.4 DBI_0.3.1
loaded via a namespace (and not attached):
[1] tools_3.1.1
Attempted solutions and respective errors:
a) TRYING TO INSTALL MonetDB.R_0.9.5.zip (beta version)
library(devtools)
remove.packages("MonetDB.R")
install_url("http://homepages.cwi.nl/~hannes/R/MonetDB.R_0.9.5.zip")
* installing *binary* package 'MonetDB.R' ...
cp: unknown option -- )
Try `/usr/bin/cp --help' for more information.
Aviso: execução do comando 'cp -R . "C:/Users/lucas_000/Documents/R/win- library/3.1/MonetDB.R" || ( tar cd - .| (cd "C:/Users/lucas_000/Documents/R/win-library/3.1/MonetDB.R" && tar -xf -))' teve status 1
ERROR: installing binary package failed
* removing 'C:/Users/lucas_000/Documents/R/win-library/3.1/MonetDB.R'
Error: Command failed (1)
b) Keeping the MonetDB.R regular version (cran) but changing the DBI to an earlier version (also sugested on SO):
remove.packages("DBI")
library(devtools)
install_url("cran.r-project.org/src/contrib/Archive/DBI/DBI_0.2-7.tar.gz")
library(DBI)
db <- dbConnect( MonetDB.R() , "monetdb://localhost:5003/RAIS" , wait = TRUE )
# gives same error as above,
Assertion Failed!
Program: C:Program Files\RStudio\bin\x64\rsession.exe
File: mapi.c, Line 91
Expression: IS_INTEGER(port)
#Then RStudio displays an error: "R Session Aborted"
MonetDB.R 0.9.5 has been released to CRAN. Windows binary distributions should be available shortly.
The error may have been in the line where you create the dbConnect.
Your code (incorrect port):
db <- dbConnect( MonetDB.R() , "monetdb://localhost:5003/RAIS" , wait = TRUE )
Correct code:
db <- dbConnect( MonetDB.R() , "monetdb://localhost:50003/RAIS" , wait = TRUE )
Another issue with this code may have been choosing dbport to be be 50 003; I believe the default is 50 000.

Resources