Run selected Rmd chunks in a single command - r

I'm experimenting with Rmd Notebooks, and I'm stuck on something that seems like it should be possible but I cannot figure out a solution at all.
Basically, I would like a functional way to run selected Rmd chunks without compiling with knitr. So I don't think using dependent chunks, caching, etc. will work here.
Here is an example notebook:
Example_Notebook.Rmd
---
title: "Example_Notebook"
output: html_notebook
---
```{r Chunk_1 , include=T}
print(1+2)
Var1 <- 'Variable From Chunk 1'
```
```{r Chunk_2 , include=T}
Var2 <- 'Variable From Chunk 2'
```
```{r Chunk_3 , include=T}
print(Var1)
Var3 <- 'Variable From Chunk 3'
print(Var3)
```
Let's say I wanted to run Chunk 1 & Chunk 3. To do it manually, I could use Ctrl+Shift+Enter while my cursor is in Chunk_1, and then Ctrl+Shift+Enter again while my cursor is in Chunk_3. This would skip Chunk_2 while still getting output for 1 & 3.
I'm looking for a way to do this in a single command/function. This would be similar to the button in RStudio "Run All Chunks Above" except obviously, I would want to skip Chunk_2.
I've tried a lot of ways to write this in a function. The closest I have gotten is with using the rstudioapi package. Here is what my function looks like:
MyNewFunction <- function(){
rstudioapi::navigateToFile( file = 'Example_Notebook.Rmd' , line = 6 )
Sys.sleep(.2)
rstudioapi::executeCommand(commandId = 'executeCurrentChunk')
Sys.sleep(.2)
print('First Command Complete')
rstudioapi::navigateToFile( file = 'Example_Notebook.Rmd' , line = 15 )
Sys.sleep(.2)
rstudioapi::executeCommand(commandId = 'executeCurrentChunk')
Sys.sleep(.2)
print('Second Command Complete')
}
MyNewFunction()
This runs, but when I look at the Example_Notebook.Rmd file, Chunk_1 displays an output, but Chunk_3 does not.
My cursor ends on line 15, so it seems like it runs through navigateToFile, Sleep commands, and print commands, but it waits for the executeCommand until the entire function has has finished.
I've also tried putting the code in the function in its own file and then using source(), as well as wrapping the code in rstudioapi::sendToConsole() but the same thing occurs.
Its almost like I need to execute 2 separate top-level tasks in a single command, but I'm not sure if that's possible or even techinically makes sense.
Looking at the C++ & java code in Rstudio, it seems like the "Run All Chunks Above" command puts all the chunks in to a scope & uses the function "executeScopedChunks". I unfortunately don't understand C++ or java at all so I don't really understand much more than that. It probably isn't helpful, but just in case, I'm looking at that here:
https://github.com/rstudio/rstudio/blob/master/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/TextEditingTarget.java#L5754
Is there any way to solve this? Any help would be very appreciated!

First, you can try the "visual" version instead of "source" version, it may make life easier:
Then, you can click the "setting" icon to change chunk 2 or whatever chunk that you do not want to run to "Show nothing (don't run the code)":
And if you want to run all the other chunks without knit, you can just click the 'run' button on the top-right of the toolbar. Click "run all" or other commands you like.

Related

How to run a chunk in R only if a variable is present in the environment? Otherwise skip to next chunk

I have a part of my RMD file that only needs to be run if a data frame is present in the environment.
So say I only need to run part of the code if data frame "Data_X" is present in the environment. Otherwise I want it to skip that chunk and go on to the next one.
How would I go about doing this?
```{r eval = exists(yourDataFrameName)}
print("The chunk is evaluated since yourDataFrameName exists")
```
Start your chunk with
if ( exists ( yourDataFrameName ) ) {
# put the chunk here
}

how to tell if code is executed within a knitr/rmarkdown context?

Based on some simple tests, interactive() is true when running code within rmarkdown::render() or knitr::knit2html(). That is, a simple .rmd file containing
```{r}
print(interactive())
```
gives an HTML file that reports TRUE.
Does anyone know of a test I can run within a code chunk that will determine whether it is being run "non-interactively", by which I mean "within knit2html() or render()"?
As Yihui suggested on github isTRUE(getOption('knitr.in.progress')) can be used to detect whether code is being knitted or executed interactively.
A simple suggestion for rolling your own: see if you can access current output format:
```{r, echo = FALSE}
is_inside_knitr = function() {
!is.null(knitr::opts_knit$get("out.format"))
}
```
```{r}
is_inside_knitr()
```
There are, of course, many things you could check--and this is not the intended use of these features, so it may not be the most robust solution.
I suspect (?) you might just need to roll your own.
If so, here's one approach which seems to perform just fine. It works by extracting the names of all of the functions in the call stack, and then checks whether any of them are named "knit2html" or "render". (Depending on how robust you need this to be, you could do some additional checking to make sure that these are really the functions in the knitr and rmarkdown packages, but the general idea would still be the same.)
```{r, echo=FALSE}
isNonInteractive <- function() {
ff <- sapply(sys.calls(), function(f) as.character(f[[1]]))
any(ff %in% c("knit2html", "render"))
}
```
```{r}
print(isNonInteractive())
```

Is it possible to display code line by line with slidify?

For teaching purpose, I would like to make some R code appear line by line for an interactive course with students. I found the interactive console of slidify (ou have to run the video to see what it means at 4'55), but I would like to know if it is possible to hide/show the code or better, to show the code line by line (an option or an animation?).
I add the code I found as demo of the interactive console below but the fact that the code appears in an interactive console is not a high requirement for me, I just want to evaluate the code after having displayed it entirely (preferably without writing multiple slides for one exercise).
--- &interactive
## Interactive Console
``{r opts.label = 'interactive', results = 'asis'}
require(googleVis)
M1 <- gvisMotionChart(Fruits, idvar = 'Fruit', timevar = 'Year')
print(M1, tag = 'chart')
```
Near the end of this tutorial, there is a great explanation of how to sequentially reveal R code and he has posted the code as well.
http://zevross.com/blog/2014/11/19/creating-elegant-html-presentations-that-feature-r-code/

Sweave/r - omit initial `>` in code chunks with `echo=true`?

I'm very new to sweave and I feel this will be an easy question, but I'm struggling to solve it myself (googling omit ">" Sweave doesn't really work because I can't search for ">"!).
I'm including a short script into my document:
<<echo=true, results=hide, eval=false>>=
# This is a simple script.
print('Hello World!\n')
#
I basically want the script to appear verbatim in the document, using whatever Sweave's "code" environment is. I don't want to evaluate it - it's just there to demonstrate how one might write a script utilising the functions in the package this document is for.
However, this produces the following in the output document:
> # This is a simple script
> print('Hello World!\n')
Is there some way to omit the > ? Is this the right way to put a script into a Sweave document, or is there some other environment that is meant to be used? (I can use a \begin{verbatim}, but it seemed to me that I should use Sweave commands if possible for code chunks).
I just want the output to be
# This is a simple script.
print('Hello World!\n')
You can try changing the prompt and continue options,
which define the > and + characters.
options(continue=" ", prompt=" ")
I like Vincent's first idea using knitr.
install.packages("knitr")
library(knitr)
Here's a sample Rnw.
\documentclass[a4paper]{article}
%\usepackage{Sweave}
\title{Test case}
\author{romunov}
\begin{document}
\maketitle
<<eval = FALSE, echo = TRUE>>=
# This is a simple script.
print('Hello World!\n')
#
\end{document}
And then
knit("coffee.Rnw")
Convert your .tex file into something pretty, and you get

Can I suppress the arrow (">") in the R/S output in Sweave?

whenever I run some R code with Sweave, it displays the terminal arrows (">") in the document. This is fine for session inputs, but sometimes I'd like to include custom functions. When arrows show up in the document, it is more difficult to copy and paste important snippets of code. Is there a quick way to do this?
I know I can run the code while suppressing the output all together, and then copy that code into a \Verbatim, but that requires extra typing.
Thanks
dumbo <- function(x)
2*x
instead of
> dumbo <- function(x)
> 2*x
Just add this to the top of the first chunk:
options(prompt=" ",continue=" ")
You can get back any moment with:
options(prompt="> ",continue="+ ")
options(prompt=" ")
You can set it back at the end.
options(prompt="> ")
This is off by default in knitr, the "next generation Sweave". Other nice features include syntax coloring and PGF integration.
Sweave code of average complexity needs only minor if any adaptions to run with knitr.

Resources