Need the filename of the Rnw when knitr runs in rStudio - r

When working on a reproducible research project, I would like to know the name of the Rnw file that is being run to use as an R variable.
This would be analogous to inserting an MSExcel filename in a footer
I am using RStudio Server on Ubuntu.
Thank you.

knitr now has a method for this: current_input()
https://github.com/yihui/knitr/issues/701

You can use the following two idioms to fetch the directory and name of the current file in knitr:
knitr:::.knitEnv$input.dir
knitr:::knit_concord$get("infile")
This is independent of RStudio, the knitr package is entirely responsible for this. These are private functions and variables that can change at any time without notice, so if you need something reliable, you might want to file an issue on GitHub.

Related

How to use objects from global environment in Rstudio Markdown

I've seen similar questions on Stack Overflow but virtually no conclusive answers, and certainly no answer that worked for me.
What is the easiest way to access and use objects (regression fits, data frames, other objects) that are located in the global R environment in the Markdown (Rstudio) script.
I find it surprising that there is no easy solution to this, given the tendency of the RStudio team to make things comfortable and effective.
Thanks in advance.
For better or worse, this omission is intentional. Relying on objects created outside the document makes your document less reproducible--that is, if your document needs data in the global environment, you can't just give someone (or yourself in two years) the document and data files and let them recreate it themselves.
For this reason, and in order to perform the render in the background, RStudio actually creates a separate R session to render the document. That background R session cannot see any of the environments in the interactive R session you see in RStudio.
The best way around this problem is to take the code you used to create the contents of your global environment and move it inside your document (you can use echo = FALSE if you don't want it to show up in the document). This makes your document self-contained and reproducible.
If you can't do that, there are a few approaches you can take to use the data in the global environment directly:
Instead of using the Knit HTML button, type rmarkdown::render("your_doc.Rmd") at the R console. This will knit in the current session instead of a background session. Alternatively:
Save your global environment to an .Rdata file prior to rendering (use R's save function), and load it in your document.
Well, in my case i found the following solution:
(1) Save your Global Environmental in a .Rdata file inside the same folder where you have your .Rmd file. (You just need click at disquet picture that is on "Global Environmental" panel)
(2) Write the following code in your script of Rmarkdown:
load(file = "filename.RData") # it load the file that you saved before
and stop suffering.
Going to RStudio´s 'Tools' and 'Global options' and visiting the 'R Markdown' tab, you can make a selection in 'Evaluate chunks in directory', there select the option 'Documents' and the R Markdown knitting engine will be accessing the global environment as plain R code does. Hope this helps those who search this info!
The thread is old but in case anyone's still looking for a solution (as I was):
You can pass an envir parameter to the render() (or knit() function) so that it can access objects from the environment it was called from.
rmarkdown::render(
input = input_rmd,
output_file = output_file,
envir = parent.frame()
)
I have the same problem myself. Some stuff is pretty time consuming to reproduce every time.
I think there could be another answer. What if you save your environment with the save.image() function to a different file than the standard .Rdata one. Then, bring it back with load().
To be sure you are using the same data, use the md5sum() from tools.
Cheers, Cord
I think I solved this problem by referring to the package explicitly in the code that is being knitted. Using the yarrr package, for example, I loaded the dataframe "pirates" using data(pirates). This worked fine at the console and within an Rstudio code chunk, but with knitr it failed following the pattern in the question above. If, however, I loaded the data into memory by creating an object using pirates <- yarrr::pirates, the document then knitted cleanly to HTML.
You can load the script in the desired environment as follows:
```{r, include=FALSE}
source("your-script.R", local = knitr::knit_global())
# or sys.source("your-script.R", envir = knitr::knit_global())
```
Next in the R Markdown document, you can use objects created in these scripts (e.g., data objects or functions).
https://bookdown.org/yihui/rmarkdown-cookbook/source-script.html
One option that I have not yet seen is the use of parameters.
This chapter goes through a simple example of how to do this.

How to keep various-topic R script at hand?

I have written and collected R code on various topics that solve particular problems at hand. I stored the R script/code in .txt files. I have now 100s of them.
How do you keep your R code at hand efficiently?
#Manetheran has the right idea: write a package. It's easy to do (especially with RStudio). Read "Writing R Extensions" and then on top of that learn about roxygen2 (which allows you to document each function in-line and avoid writing .Rd files).
Then you can use devtools to load your package locally, or once it's stable if you think other people can use the functions you can submit your package to CRAN.
I prefer to keep it simple. I use Total Commander and when I need an example which uses some R function, I just do Alt-F7 and search for *.R files which contain the desired string.
I use RStudio and have created two or three basic scripts. I save my much-used functions in the basic script that is most appropriate. Then, at the start of an RStudio script for a project, I source one or more of the basic scripts as is appropriate.

Compiling *.Rnw files with knitr --without Rstudio

I would like to use knitr to create presentations that embed R objects and code.
For IT reasons I am restricted to vim, so i have found the available Rstudio+knitr examples fairly unhelpful. The vim section of the knitr documents is also very skinny, and therefore unhelpful.
Is someone able to provide some guidance on how to compile a *.Rnw or *.Rmd file using knitr (or alternately point me to a decent online tutorial?) using some combination of vim, R, and the command line?
thanks in advance
Instead of going through Rstudio, you can use the functions in the knitr package directly. There are some options you can tweak, but to get started, all you have to do is call the knit() function on your .Rnw file:
library(knitr)
knit('my_input.Rnw')
If you're missing some of Rstudio's features, it's worth remembering that most of them are just making use of things that are already available in various R packages, so you can usually find a way to use them when you don't have Rstudio available.

Sweave syntax highlighting in output

Has anyone managed to get color syntax-highlighting working in the output of Sweave documents? I've been able to customize the output style by adding boxes, etc. in the Sweave.sty file as follows:
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontseries=bc,frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontseries=bc}
And I can get the minted package to do syntax highlighting of verbatim-code blocks in my document like so:
\begin{minted}{perl}
use Foo::Bar;
...
\end{minted}
but I'm not sure how to combine the two for R input sections. I tried the following:
\DefineVerbatimEnvironment{Sinput}{minted}{r}
\DefineVerbatimEnvironment{Scode}{minted}{r}
Any suggestions?
Yes, look at some of the vignettes for Rcpp as for example (to pick just one) the Rcpp-FAQ pdf.
We use the highlight by Romain which itself can farm out to the hightlight binary by Andre Simon. It makes everything a little more involved---Makefiles for the vignettes etc pp---but we get colourful output from R and C/C++ code. Which makes it worth it.
I have a solution that has worked for me, I have not tried it on any other systems though so things may not work out of the box for you. I've posted some code at https://gist.github.com/797478 that is a set of modified Rweave driver functions that make use of minted blocks instead of verbatim blocks.
To use this driver just specify it when calling the Sweave function with the driver=RweaveLatexMinted() option.
Here's how I've ended up solving it, starting from #daroczig's suggestion.
\usepackage{minted}
\renewenvironment{Sinput}{\minted[frame=single]{r}}{\endminted}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{}
While I was at it, I needed to get caching working because I'm using large data sets and one chunk was taking around 3 minutes to complete. So I wrote this zsh shell function to process an .Rnw file with caching:
function sweaveCache() {
Rscript -e "library(cacheSweave); setCacheDir(getwd()); Sweave('$1.Rnw', driver = cacheSweaveDriver)" &&
pdflatex --shell-escape $1.tex &&
open $1.pdf
}
Now I just do sweaveCache myFile and I get the result opened in Preview (on OS X).
This topic on tex.StackExchange might be interesting for you, as it suggest loading the SweaveListingUtils package in R for easy solution.

Make Sweave + RweaveHTML put all graphics in a specified folder

As a refinement of this question, does anyone know how to tell Sweave (or better the driver) to put all the graphics in a specific directory when using the RweaveHTML driver from the R2HTML package? I can't find any option for that :(
Sweave responds to the prefix.string option for figures. E.g. in one recent document I use
\SweaveOpts{engine=R,eps=FALSE,echo=TRUE,prefix.string=figures/chart}
which leads to files figures/chart-chunkname.pdf where I use chunkname as the identifier in the Sweave code snippet. I suspect the same may help for R2HTML but I have not tried that driver.

Resources