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

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/

Related

Using R/Markdown fails inside learnr question

Motivation: I want to write an interface that uses questions from the R package exams in learnr questions/quizzes. In R/exams each question is either an R/Markdown (Rmd) or R/LaTeX (Rnw) file with a certain structure specifying question, solution, and further meta-information. The questions can contain R code to make them dynamic, e.g., sampling numbers or certain text building blocks etc. Hence, the workflow is that first the questions are run through knitr::knit or utils::Sweave and then embedded in a suitable output format.
Problem: When I rmarkdown::run("learnr+rexams.Rmd") a learnr tutorial that dynamically produces a question or quiz from an Rmd exercise I get the error:
Error in if (grepl(not_valid_char_regex, label)) { :
argument is of length zero
The code for a simple reproducible example learnr+rexams.Rmd is included below.
The reason for the error appears to be that learnr runs a function verify_tutorial_chunk_label() that tries to assure the the learnr R chunk labels are well formatted. However, confusion is caused by the chunks that are run by the R/exams package, unnecessarily leading to the error above.
Workarounds: I can disable the verify_tutorial_chunk_label() in the learnr namespace and then everything works well. Or I can use Rnw instead of Rmd exercises and then learnr does not conflict with Sweave(). Also, when I run my code outside of a learnr tutorial it works fine.
Question: Can I do anything less invasive to make exams cooperate with learnr? For example, setting some appropriate knitr options or something like that?
Example: This is the source for the minimal learnr tutorial learnr+rexams.Rmd that replicates the problem. Note that everything is very much simplified and only works for certain R/exams exercises, here using the function exercise template that ships with R/exams.
---
title: "learnr & R/exams"
output: learnr::tutorial
runtime: shiny_prerendered
---
```{r exams2learnr, include = FALSE}
exams2learnr <- function(file) {
x <- exams::xexams(file)[[1]][[1]]
x <- list(text = x$question, type = "learnr_text",
learnr::answer(x$metainfo$solution, correct = TRUE))
do.call(learnr::question, x)
}
## assignInNamespace("verify_tutorial_chunk_label", function() return(), ns = "learnr")
```
```{r rfunctions, echo = FALSE, message = FALSE}
exams2learnr("function.Rmd")
```
Running this tutorial (as noted above) replicates the error. To avoid it I can either uncomment the assignInNamespace() call or alternatively replace "function.Rmd" by "function.Rnw".
The problem is that by the time learnr::question() is called, knitr is no longer able to find the chunk label for the chunk where exams2learnr() was called. You can get around this by setting the current chunk label before calling do.call(learnr_question, x):
exams2learnr <- function(file, label = knitr::opts_current$get("label")) {
force(label)
x <- exams::xexams(file)[[1]][[1]]
x <- list(
text = x$question,
type = "learnr_text",
learnr::answer(x$metainfo$solution, correct = TRUE)
)
knitr::opts_current$set(label = label)
do.call(learnr::question, x)
}
This also lets you set the label dynamically if you want, which becomes the ID of the question in learnr.

Create a carousel in Rmarkdown?

Is there any quick and easy way to create a simple carousel in an Rmarkdown doc?
What I know so far
I found slickr but run into errors setting options and knitting (the errors could be specific to me / mac - I am not sure at this point).
I believe it would be possible to hard code html/javascript into the RMarkdown doc i.e. the same way a carousel would be done in any other (regular) html document (i.e. using the html code here)- but I wonder if there's a native (R) way?
Example use
In my particular use case, I'm trying to display multiple complicated ggplots which are each sufficiently complex to make them require their own space (i.e. not faceted or grid.arrange as the size of each plot will get too small to read
Notes
Here is the slickr code I tried
library(texPreview)
library(slickR)
objpath <- file.path(getwd(),"slickr_files/figure-html")
if(!dir.exists(objpath)) { dir.create(objpath,recursive = TRUE) }
tex_opts$set(
fileDir = objpath, # path to save output
returnType = 'html', # return images ready for html
imgFormat = 'png' # return png images
)
knitr::kable(mtcars,'latex') %>%
texPreview::tex_preview(stem = 'kable-1')
# ! LaTeX Error: File `standalone.cls' not found.
A side note, if there's a better way of providing many (e.g. > 3) large, detailed plots that doesn't involve faceting, grid.arrange, or (my current preferred option) tabbing, please give a suggestion as a comment
The example works fine for me. Be sure to save your plots in the folder slickr_files/figure-html.
Then run:
```{r}
slickR::slickR(
list.files(objpath,full.names = TRUE,pattern = 'png'),
height = 200,
width = '95%')
```

Comments in Rpres

I'm trying to put a comment in my Rpres script, but I don't want that comment to appear in the final presentation. I know that in an R script, the comments are expressed by #comment. But how it would be in Rpres?
For example, for a specific slide:
Title of slide:
```{r}
vector <- c(1,2,4)
dataframe <- data[data$line == 4,]
table <- table(dataframe$line2)
```
I want to add a comment here about a code line (this comment would be visible only for me in my Rpres script, but not on the presentation display).
Then I explain the results (this part would be on the presentation display).
Is there a special key like % or # that would make that work?
There is more than one way of doing this, what I found to be fairly generic is the following format:
[//]: # ("this is just a comment")

How to save a plot as image on disk from Viewer in RStudio?

Summary: my ultimate goal is to use rCharts, and specifically Highcharts, as part of a ReporteRs PowerPoint report automation workflow. One of the charts I would like to use is rendered as html in the Viewer pane in Rstudio, and addPlot(function() print(myChart)) does not add it to the PowerPoint. As a workaround, I decided to try to save myChart to disk, from where I could just add it to the PowerPoint that way.
So my question is really, How do I get my html image into my ReporteRs workflow? Either getting it saved to a disk, or getting it to be readable by ReporteRs would solve my problem.
This question is really the same as this one, but I'm using rCharts, specifically the example found here:
#if the packages are not already installed
install.packages('devtools')
require(devtools)
install_github('rCharts', 'ramnathv')
#code creates a radar chart using Highcharts
library(rCharts)
#create dummy dataframe with number ranging from 0 to 1
df<-data.frame(id=c("a","b","c","d","e"),val1=runif(5,0,1),val2=runif(5,0,1))
#muliply number by 100 to get percentage
df[,-1]<-df[,-1]*100
myChart <- Highcharts$new()
myChart$chart(polar = TRUE, type = "line",height=500)
myChart$xAxis(categories=df$id, tickmarkPlacement= 'on', lineWidth= 0)
myChart$yAxis(gridLineInterpolation= 'circle', lineWidth= 0, min= 0,max=100,endOnTick=T,tickInterval=10)
myChart$series(data = df[,"val1"],name = "Series 1", pointPlacement="on")
myChart$series(data = df[,"val2"],name = "Series 2", pointPlacement="on")
myChart
So if I try
> png(filename="~/Documents/name.png")
> plot(myChart)
Error in as.double(y) :
cannot coerce type 'S4' to vector of type 'double'
> dev.off()
I get that error.
I've looked into Highcharts documentation, as well as many other potential solutions that seem to rely on Javascript and phantomjs. If your answer relies on phantomjs, please assume I have no idea how to use it. webshot is another package I found which is even so kind as to include an install_phantomjs() function, but from what I could find, it requires you to turn your output into a Shiny object first.
My question is really a duplicate of this one, which is not a duplicate of this one because that is how to embed the html output in Rmarkdown, not save it as a file on the hard drive.
I also found this unanswered question which is also basically the same.
edit: as noted by #hrbrmstr and scores of others, radar charts are not always the best visualization tools. I find myself required to make one for this report.
The answer turned out to be in the webshot package. #hrbrmstr provided the following code, which would be run at the end of the code I posted in the question:
# If necessary
install.packages("webshot")
library(webshot)
install_phantomjs()
# Main code
myChart$save("/tmp/rcharts.html")
webshot::webshot("/tmp/rcharts.html", file="/tmp/out.png", delay=2)
This saves the plot to the folder as an html, and then takes a picture of it, which is saved as a png.
I can then run the ReporteRs workflow by using addImage(mydoc, "/tmp/out.png").

Synchronization of dygraph in R not working

I am running the dygraph example provided by the following RSTUDIO help page.
http://rstudio.github.io/dygraphs/gallery-synchronization.html
When I run the following code, I get individual plots for each dygraph separately.
dygraph(ldeaths, main = "All", group = "lung-deaths")
dygraph(mdeaths, main = "Male", group = "lung-deaths")
dygraph(fdeaths, main = "Female", group = "lung-deaths")
I don't get the synchronized plots as shown in the help page.
The "group" variable "lung-deaths" is not part of the xts object.
Please let me know if I am missing something basic here.
Thanks
Pradeep
To plot multiple dygraphs in the same RStudio window you must first create a list of dygraphs objects, and then render the dygraphs list using package htmltools. Yihui Xie from RStudio provided the answer here:
Yihui Xie answer (but without grouping).
I answered similar questions here: my answer, and here: my answer.
Here is working R code that produces grouped (synchronized) dygraphs plots:
# create a list of dygraphs objects
library(dygraphs)
library(htmltools)
dy_graph <- list(
dygraphs::dygraph(ldeaths, main = "All", group = "lung-deaths"),
dygraphs::dygraph(mdeaths, main = "Male", group = "lung-deaths"),
dygraphs::dygraph(fdeaths, main = "Female", group = "lung-deaths")
) # end list
# render the dygraphs objects using htmltools
htmltools::browsable(htmltools::tagList(dy_graph))
The above R code produces the following grouped (synchronized) dygraphs plots:
(I can't add a comment because I do not have enough reputation yet.)
By checking the code behind dygraph's gallery (right-click on a graph and choose "Inspect" in Google Chrome), it looks like each graph is its own html element. Therefore they can be synchronized ONLY if they are together on the same html page. This will not work in Rstudio.
If it is possible to plot several dygraph() graphs at once (as asked by #schlusie in this SO question dygraph in R multiple plots at once but with no answer yet), then synchornization might work in Rstudio.
Maybe people who know about css have other opinions.
I encountered the same problem. I could not reproduce the dygraph example on synchronization provided by the gallery help page in RStudio.
However, for my needs of pure visualization I found a workaround discussed on github:
Specify your dygraph objects in a R-script (e.g myscript.R) according to your needs and assign them to variables (e.g. d1 and d2).
d1 = dygraph(ldeaths, main = "All", group = "lung-deaths")
d2 = dygraph(mdeaths, main = "Male", group = "lung-deaths")
Open a R-markdown document, source() your R-script in a code cell and call the variables.
{r, echo=FALSE}
source("myscript.R")
d1
d2
Finally, render the R-markdown document to a html file (Kint to html). By setting echo=FALSE you suppress the alphanumeric output and end up with a html document with synchronized dygraph plots.

Resources