Running R file to render bookdown output from command line (Terminal) - r

I'm trying to run an R file from the command line (from Terminal -- on macOS 10.13.3).
Following the directions in this helpful Q & A, I added #! [path/to/file.R] as the first line of the R file.
When I then type Rscript [path/to/file.R] in Terminal, a part of the file to test that it worked seems to run (I added a print() statement), however, the next line:
rmarkdown::render_site(output_format = 'bookdown::pdf_book', encoding = 'UTF-8')
Leads to this error:
Error in rmarkdown::render_site(output_format = "bookdown::pdf_book", :
No site generator found.
Why does the print() statement appear to work fine, but this line - to render a bookdown book - does not?
The file I'm trying to run is on GitHub here.

For Markdown I have had the following script in the examples directory of littler for about 1 1/2 years, and rendered hundreds of times with it.
Note it calls rmarkdown::render() yet you want a bookdown format, so methinks you may need to write a very similar script calling bookdown::render_book() or a similar function.
You can of course do exactly the same as a one-liner from Makefiles, and many people do. Here is one which will map all Rmd file to pdf documents (which is my standard workflow, I don't do much html):
sources := $(wildcard *.Rmd)
slides := $(sources:.Rmd=.pdf)
all: ${slides}
%.pdf: %.Rmd
Rscript -e "rmarkdown::render(\"$<\", clean=TRUE)"
Because my editor has a shortcut for invoking make this is particularly handy.
Lastly, for Rscript (available everyhere) you'd do #!/usr/bin/env Rscript or possibly the direct path to Rscript.

You could use a simple script like this that you save to compile.book.sh for example.
#!/bin/sh
## Get the path to the book
BOOK_PATH=$1
## Get the current path
CURRENT_PATH=$(pwd)
## Get to the right path
cd ${BOOK_PATH}
## Compile the book
R -e 'rmarkdown::render_site(output_format = 'bookdown::pdf_book', encoding = 'UTF-8')'
## Get back to the previous path
cd ${CURRENT_PATH}
You can then execute the compilation as follows from wherever in your machine (from the terminal):
sh compile.book.sh path/to/Rfolder
With path/to/Rfolder being the folder where your index.Rmd is.

Related

How to address an Rscript parse error: premature EOF?

Running my working R script in the windows command line (cmd) using Rscript results in a parsing error (premature EOF).
When I run the script in RStudio, it compiles and runs as expected.
I have read the Rscript page in R documentation, and I see that the problem must be due to spaces in my script itself, which probably make it into the cmd console somehow during parsing, but that's as far as I get.
Or should I have done something with the #! functionality mentioned therein?
I am trying to run it on cmd:
Rscript .\start_app.r
I am in the right working directory, and have set the folder containing Rscript in my environment.
The script is too long to share, and I am too inexperienced to give you the parts that make it break (otherwise I wouldn't be here), but it is full of functions, if statements and the like, that use curly brackets and are indented. I also often include empty rows (someteimes indented) for readability. It makes use of the shiny-package. An example could be:
islocal = nchar(Sys.getenv("LOCAL"))>1 | interactive()
if (islocal){
source('../../path/app/variables/styling.R')
} else {
source('./variables/styling.R')
}
As the example above, it also includes other R code called via source()
Can that somehow make it to the cmd line and be incorrectly compiled?
I get the following messages:
Error: parse error: premature EOF
(right here) ------^
Execution halted
Not enough memory resources are available to process this command.
(I guess the second message is an unrelated issue, but include it here just to be sure.)
As suggested in a comment, the solution was changing the encoding.
As mentionned by the requestor himself, Using "Save with Encoding -> ISO-8895-1 (System default)" solves the issue.

How to drop into R shell after executing commands from file in R

In Python, running the interpreter with the -i flag first executes the script, then drops back into the interpreter
python -i hello.py
Hello world
>>> print("Python ftw")
Python ftw
>>>
which allows me to type commands and reach the variables after execution.
With R, this seems to be of great difficulty. I have been searching online for some time, and am surprised to see there is not so many results with the keywords "R run file shell interpreter".
With R, you can use
$ R -f myfile.R which executes and then exits the interpreter
$ Rscript myfile.R which still does the same thing.
Even worse, it does not plot when run like this and just exits without showing any signs that something has been plotted.
So, to repeat my question:
How do I make R to drop into the R shell after running commands from a file, a.k.a. a script?
Concurrently, how can I make R really plot the plots and not close them off immediately?
I can do these with Python, MATLAB, Octave, Ruby and many others, and should be able to do with R too.
I will answer your two questions separately:
How do I drop into a shell after my script has executed?
The function "browser" called with no arguments will allow to to drop into a shell on the line that it's called. Appending this to your script should do the trick.
How do I save graphics when not run in interactive mode?
First, check that there isn't a pdf file being created in your working directory. Depending on how you're running R, I believe it may be named "Rplots.pdf". Personally, however, I prefer to explicitly save graphics to a particular file, as such:
pdf("temp.pdf")
plot(rnorm(100))
dev.off()
which will save the plot in a new file called temp.pdf (and will overwrite any existing file by that name, so watch out).
Functions analagous to "pdf" exist for other image formats if you would prefer that.

workflow between Latex and R screwed

Trying to write my second Latex file
\documentclass{article}
\title{simple Sweave script}
\usepackage{/Users/Brenden/Documents/R/R-2.15.1/share/texmf/tex/latex/Sweave}
\begin{document}
\maketitle
This is a simple script to demonstrate Sweave. Let's
begin by generating some results
<<>>=
x=rnorm(30)
y=rnorm(30)
mean(x)
cor(x,y)
#
and follow that up with some random text
\end{document}
File saved with .Rnw as extension. I could then use Sweave under R to convert the file to tex. I then run pdflatex under cmd to get my .pdf file. R is stored under /Users/Brenden/Documents. MiKTex is stored under /Users/Brenden/Desktop.
It is said that usually the line of "usepackage" is not needed, as when I run Sweave under R, a line of "usepackage{Sweave}" will be added to the tex file which is stored under /Users/Brenden/Documents. However, if I don't put in userpackage line, when I run pdflatex under cmd (either under /Documents or /Desktop), I got a messsage that says "Sweave.sty not found". So I have been through this trouble by always adding a line of usepackage with a detailed path to help circumvent the problem. Although the "Sweave.sty not found" problem is circumvented, I do notice that when I run pdflatex under cmd, I got the response
LaTeX Warning: You have requested package '/Users/Brenden/Documents/R/R-
2.15.1/share/texmf/tex/latex/Sweave', but the package provides "Sweave'.
Then it runs through several files with .sty under MiKTex
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\base\ifthen.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\graphicx.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\keyval.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\graphics.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\trig.sty)
...
to eventually create a .pdf
From another post on Stackoverflow, it is said, "That path is set automatically when you install LaTeX; it's your personal texmf tree and you can put any style or class files you want LaTeX to find there. The directory names don't matter, it searches recursively in them for Sweave.sty". To me, however, clearly my MiKTex could not find the Sweave.sty unless I specify the path. And even with the path specification, LaTex still gives me a warning. Could someone explain to me where I screwed up (during installing MiKTex, perhaps? ) so that I could help MiKtex find its way to Sweave without my specifying the path?
Thank you.
In the MiKTeX Settings program, there is a tab called "Roots". It is there that you can specify where additional .sty files can be found. In your case, I believe that you will want to add C:\Users\Brenden\Documents\R\R-2.15.1\share\texmf as an additional root. Doing this, any of the TeX programs will be able to find Sweave.sty whether run from inside R or from the command line.
It is annoying to be always distracted by little devils like this (new concept texmf tree, endless environment variables TEXINPUTS, SWEAVE_STYLEPATH_DEFAULT, ...). You will never worry about LaTeX packages if you use knitr, and if you like the Sweave style, you can simply put render_sweave() in the document like:
\documentclass{article}
\title{simple Sweave script}
<<setup, include=FALSE>>=
render_sweave()
#
\begin{document}
\maketitle
This is a simple script to demonstrate Sweave. Let's
begin by generating some results
<<>>=
x=rnorm(30)
y=rnorm(30)
mean(x)
cor(x,y)
#
and follow that up with some random text
\end{document}
Save it as, say, test.Rnw and compile it with
library(knitr); knit('test.Rnw') # or knit2pdf('test.Rnw')
And I guess you are probably better off without render_sweave() (i.e. use the default LaTeX style in knitr).
I suspect the path referred to in the other post is the path to your personal texmf tree, which is not where Sweave puts it. One option is to move it to your personal texmf tree, but the usual method nowadays, I believe, is to run pdflatex from within R, like this:
texi2dvi("foo.tex", pdf = TRUE)
I think you can also have Sweave add the full path automatically by adding
export SWEAVE_STYLEPATH_DEFAULT="TRUE"
to your .bashrc file, or whatever the equivalent would be on your system.
At the command line, R CMD sets up the environment with variables appropriate for running R, for instance on Windows
C:\Users\mtmorgan> "c:\Program Files\R\R-2.15.1\bin\R" CMD set
includes (this is not found if one types set at the command line)
TEXINPUTS=.;c:/PROGRA~1/R/R-215~1/.1/share/texmf/tex/latex;
and so
C:\Users\mtmorgan> "c:\Program Files\R\R-2.15.1\bin\R" CMD pdflatex myfile.tex
will find Sweave.sty. Also, tools::texi2dvi can be invoked from within R.
I eventually end up with the following solution:
install.packages("tinytex")
require("tinytex")}
install_tinytex(force = TRUE)
Sweave( "Report.Rnw" , encoding = "utf8" )
xelatex('Report.tex')
This code install TinyTex, then you can compile with pdflatex(), xelatex() or lualatex().

What is the knitr equivalent of `R CMD Sweave myfile.rnw`?

What is the command-line knitr equivalent of R CMD Sweave myfile.rnw?
The general solution (works regardless of the R version):
Rscript -e "library(knitr); knit('myfile.Rmd')"
Since R 3.1.0, R CMD Sweave has started to support non-Sweave documents (although the command name sounds a little odd), and the only thing you need to do is to specify a vignette engine in your document, e.g.
%\VignetteEngine{knitr::knitr}
To see the possible vignette engines in knitr, use
library(knitr)
library(tools)
names(vignetteEngine(package = 'knitr'))
# "knitr::rmarkdown" "knitr::knitr" "knitr::docco_classic" "knitr::docco_linear"
I have a knitme.R script:
library(knitr)
render_html()
source("hooks.R") # mods to defaults
inFile = commandArgs(trailingOnly=TRUE)[1]
outFile = commandArgs(trailingOnly=TRUE)[2]
knit(inFile,output=outFile)
so I can then do
Rscript knitme.R $SOURCE $TARGET
Where $SOURCE and $TARGET are as required.
You could also integrate this into Make, so you had a rule that all you had to do was:
make myfile.html
and it would go to myfile.Rhtml and produce the HTML file. Adjust to make PDF from .Rnw
I'm using it with SCons instead of Make, so I have a Sconscript file which is a bit more complex (partly because I've only just started learning to use SCons, so it might be a bit crufty)
env=Environment()
bld = Builder(action = '/usr/bin/Rscript knitme.R $SOURCE $TARGET',
suffix='.html',
src_suffix='Rhtml')
env.Append(BUILDERS = {'Knit' : bld})
env.Knit(source='test.Rhtml',target='test.html')
Then all I need to do is:
scons test.html
and I get test.html built from test.Rhtml if test.Rhtml has changed.
This is all part of a Sconstruct file that builds an entire web site and copies it to a server, based on all sorts of other dependencies..
Drifting off-topic now...
To add on to the other answers, if you want to knit/render the file and open the output all in one line you can use:
Rscript -e "rmarkdown::render('file.Rmd')" & open file.pdf
I prefer to do it all in one line because it's simpler to run as a reusable Vim command.
You can also replace open with a specific application if you want to use your system's non-default. I tend to use this if I'm on Windows and want to use Sumatra to overwrite a PDF output that's currently open (so I don't have to remember to close it every time).
R CMD knit file.Rmd
is the direct equivalent to R CMD Sweave file.Rmd
Lately, there are enhanced functions in rmarkdown and knitr for this kind of dirty work. For slides, I've been using the Rmarkdown YAML header to designate the intended output format and the command line is basic, like
R -e "library(rmarkdown); render(\"file.Rmd\")"

More efficient R / Sweave / TeXShop work-flow?

I've now got everything to work properly on my Mac OS X 10.6 machine so that I can create decent looking LaTeX documents with Sweave that include snippets of R code, output, and LaTeX formatting together. Unfortunately, I feel like my work-flow is a bit clunky and inefficient:
Using TextWrangler, I write LaTeX code and R code (surrounded by <<>>= above and # below R code chunk) together in one .Rnw file.
After saving changes, I call the .Rnw file from R using the Sweave command
Sweave(file="/Users/mymachine/Documents/Assign4.Rnw",
syntax="SweaveSyntaxNoweb")
In response, R outputs the following message:
You can now run LaTeX on 'Assign4.tex'
So then I find the .tex file (Assign4.tex) in the R directory and copy it over to the folder in my documents ~/Documents/ where the .Rnw file is sitting (to keep everything in one place).
Then I open the .tex file (e.g. Assign4.tex) in TeXShop and compile it there into pdf format. It is only at this point that I get to see any changes I have made to the document and see if it 'looks nice'.
Is there a way that I can compile everything with one button click? Specifically it would be nice to either call Sweave / R directly from TextWrangler or TeXShop. I suspect it might be possible to code a script in Terminal to do it, but I have no experience with Terminal.
Please let me know if there's any other things I can do to streamline or improve my work flow.
I use a Makefile of the following form for my Sweave documents:
pdf: myfile.tex
R CMD texi2pdf myfile.tex
myfile.tex: myfile.Rnw
R CMD Sweave myfile.Rnw
Then I can build the document in one step in the Mac OS Terminal by running the command make pdf
I'm sure there is a way to bring this closer to your one-click goal in Mac OS X, but this works well enough for me.
One-click Sweaving is easy to do in TeXShop using the Sweave.sh script by Gregor Gorjanc.
Get it from http://cran.r-project.org/contrib/extra/scripts/Sweave.sh and put it in your ~/Library/TeXShop/bin/ folder.
Then add the following files to your ~/Library/TeXShop/engines/ folder:
As Sweave.engine:
#!/bin/bash
~/Library/TeXShop/bin/Sweave.sh -ld "$1"
As SweaveNoClean.engine:
#!/bin/bash
~/Library/TeXShop/bin/Sweave.sh -nc -ld "$1"
You'll have to set the permissions on Sweave.sh and the two engine files to allow execution.
To Sweave with one click, restart TeXShop after adding these files, open the Sweave document (with Rnw extension) and in the dropdown menu above the document window, change it from LaTeX to Sweave or SweaveNoClean.
BEWARE: The "Sweave" option wll clean up after itself, deleting all the extra files LaTeX and Sweave creates. If your file is called myfile.Rnw, this will include files called myfile.R and myfile.tex. So a word to the wise: make sure the basename of your Rnw file is unique; then nothing unexpected will be written over and then deleted.
The SweaveNoClean option does not clean up after itself. This makes sure you don't delete anything unexpected; though it could still write over a file called myfile.tex if you Sweave a myfile.Rnw. This also doesn't delete any graphics that have been created, in case you want to have them separate from your full typeset document.
On the bash shell command line:
R CMD Sweave foo.Rnw && pdflatex foo.tex
Runs Sweave, and if that succeeds it goes on to do pdflatex. Out pops a pdf. If you've got this in a bash Terminal then just hit up-arrow to get it back and do it again. And again. And Again.
Makefile solution also good.
RStudio has a button that does this in one go. One caveat is that it runs in its own session, so any workspace variables you may have set are ignored.
Just a note: you can actually call things like pdflatex etc. directly from R using texi2dvi (in the tools package). For example:
Sweave(file="/Users/mymachine/Documents/Assign4.Rnw")
texi2pdf("Assign4.tex")
would compile your Rnw file into a pdf. Thus, no need to leave R to handle the tex->pdf step.
I use these (saved as sweave.engine and sweavebibtex.engine) for custom engines in texshop. I usually work up a code chunk in R, then copy the block into the rnw file I have open in texshop. I'd love a solution that lets me do syntax highlighting and spelling correction of R and tex in the same document (that isnt emacs).
#!/bin/bash
echo 'SWEAVE | PDFLATEX. Custom engine--Akasurak-16Nov2009'
export PATH=$PATH:/usr/texbin:/usr/local/bin
R CMD Sweave "$1"
pdflatex "${1%.*}"
and the second, for doing bibtex as well:
#!/bin/bash
date
before="$(date +%s)"
echo 'SWEAVE | PDFLATEX | BIBTEX | PDFLATEX | PDFLATEX. Custom engine--Akasurak-16Nov2009'
#Updated 20Jul2010 for auto including Sweave.sty
export PATH=$PATH:/usr/texbin:/usr/local/bin
R CMD Sweave "$1"
R CMD pdflatex "${1%.*}"
bibtex "${1%.*}.aux"
R CMD pdflatex "${1%.*}"
R CMD pdflatex "${1%.*}"
after="$(date +%s)"
elapsed_seconds="$(expr $after - $before)"
date
echo Elapsed time '(m:s)': $(date -r $elapsed_seconds +%M:%S)
Can't say they are the best way of doing things, but they do work.
I use either Aquamacs or Eclipse to do the editing of the .Rnw file, then I use the following shell function to compile & view it:
sweaveCache () {
Rscript -e "library(cacheSweave); setCacheDir(getwd());
Sweave('$1.Rnw', driver = cacheSweaveDriver)" &&
pdflatex --shell-escape $1.tex &&
open $1.pdf
}
Notice that I'm using the cacheSweave driver, which helps avoid constantly re-executing code sections that take a long time to run.
BTW, I'm also trying to switch over to Babel instead of Sweave; not sure which I'll end up using more often, but there are definitely aspects of Babel that I like.
The best solution is here: you create a new *.engine for TeXShop to use, then typeset using the shortcut or the 1 button.
http://cameron.bracken.bz/sweave-for-texshop
Cameron is also very responsive, so I highly recommend his solution.
If you are open to switching to a (paid) solution, TextMate has a Sweave plugin that takes you from .Rnw to PDF in one step: Sweave, typeset, and view. Combined with Skim, which can be configured to reload PDFs, it makes tweaking files pretty easy.
I had this same issue (I use Mac OSX) and I opted to download Eclipse Classic 3.6.2. and then installed the StatET plugin. It's a bit hairy to get set up but once you do this environment is nice because you can one-click compile your .Rwn Sweave document using pdflatex and set options for your favorite viewer so the .pdf automatically pops up when you compile like it does in TeXShop. You can do this in TeXShop as well, but TeXShop is lousy for debugging .Rnw files and it doesn't highlight the R-code in the .Rwn file. In Eclipse you can customize the syntax highlighting (not the greatest from the Texclipse end, but ok) so that you can easily distinguish between your R and LaTeX code. You can also launch the R console from within Eclipse and it has a graphical object browser. Anyway, I could go on. If you want details about how to get it all installed, message me.
Guess I'm late to the party on this, but I put together a webpage that documents my Sweave workflow based on Eclipse (with one-touch sweave):
http://www.stanford.edu/~messing/ComputationalSocialScienceWorkflow.html

Resources