2 Knitr/R Markdown/Rstudio issues: Highcharts and Morris.js - r

I'm presently trying to replicate a few different types of rCharts using my own data. The first is a HighCharts graph with the following code:
````{r}
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8a.csv")`
require(slidify)
require(rCharts)
require(rHighcharts)
```
```{r}
x<-data.frame(blah,stringsAsFactors=TRUE)
colnames(x)<-substr(colnames(x),2,5)
a<-rHighcharts:::Chart$new()
a$chart(type="column")
a$title(text="Percent of Students on Grade Level on G8 FCAT for Reading (1), Math (2), Writing (3), and Science (4)")
a$xAxis(categories=rownames(x))
a$yAxis(title=list(text="Percent Proficient"))
a$data(x)
```
When this is run as a chunk, the graph is produced nicely, but when I use Knit HTML in markdown, it sticks at the preview stage for a while and when I terminate it, it gives a "status 15" message, which I'm unclear what that means and how it should be resolved.
A second graph I'm trying is a Morris.js graph in Markdown with knitr. I took my R code and put into R Markdown which looks like:
```{r}
library(slidify)
library(knitr)
library(rCharts)
library(RColorBrewer)
library(reshape2)
setwd("C:/Users/ypetscher/Dropbox/R fun")
blah<-read.csv("g8.csv")
blah
```
```{r}
m2<-mPlot(x="year",y=colnames(blah)[-1],data=blah, type="Bar")
m2$set(barColors=brewer.pal(4,"Spectral"))
m2$set(xlab="Year")
m2$set(postUnits="%")
m2$set(hideHover="auto")
m2
```
When I run the chunks, it produces a nice graph the way I expected with an html file of (file:///C:/Users/ypetscher/AppData/Local/Temp/RtmpW4q3ka/filed284f137718.html); however, when I click on Knit HTML, I obtain a file which includes the code, but doesn't produce the graph. Additionally, when Google Chrome comes up I receive an error of :
"No webpage was found for the web address:
file:///C:/Users/YPETSC~1/AppData/Local/Temp/Rtmpk1Pfbp/filee0c383670e0.html
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be
found."
Any help would be greatly appreciated in diagnosing these issues. Thank you much!

NOTE: This is the same solution I posted in the knitr google group.
To get rCharts to work with knit2html, you will need to use the print method with the argument include_assets = TRUE. This is because knitr will not add the js and css assets required by an rCharts plot automatically. Here is a minimal working example.
## MorrisJS with Knit2HTML
```{r results = 'asis', comment = NA}
require(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',
data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1$print('chart2', include_assets = TRUE)
```
Note that you need to use m1$print('chart2', include_assets = TRUE, cdn = TRUE) if you intend to publish your chart on RPubs, for otherwise the JS and CSS assets will be served from your local library.
Hope this helps.

Related

Dynamic plots and tables inside Rmarkdown

I am new to Rmarkdown and shiny and forgive me for some naive questions. I have build a code in two parts first where I do all the processing and second where I call the Rmarkdown to knit it.
The first code example.R is as follows and works fine independently (with only glitch of plots being trimmed from sides):
# Create a label for the knitr code chunk name
## #knitr ExternalCodeChunk020
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
The second part of the code (mrkdwn.Rmd) is where I try to knit and generate Rmarkdown report:
---
title: "Code Chunks"
author: "Author"
date: "November 13, 2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::read_chunk("example.R")
```
This first code chunk prints the externally located code,
but it does not execute the code. The next code chunk
executes the externally located code, but it does not print code
itself. Text output is suppressed, and figures are plotted,
but only after all of the code is executed.
```{r DisplayCodeChunk, eval = FALSE, echo = FALSE}
<<ExternalCodeChunk020>>
```
```{r RunCodeChunk, echo = FALSE, eval = TRUE, results = 'hide'}
<<ExternalCodeChunk020>>
```
the output doesn't contain plots. I am not sure what is going wrong, could anyone of you help me in fixing this.
I know that an easy fix is to put both parts of the code together inside the Rmarkdown like this:
---
title: "test3"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
library(Seurat)
library(tidyverse)
library(sleepwalk)
library(gridExtra)
library(plotly)
library(DT)
# Set up some sample data
data(mtcars)
# Display the xvars
# Note that I don't really want to display the xvars, but this line is included
# to demonstrate that text output won't show up in the RMarkdown in this example.
a <- ggplotly(ggplot(mtcars, aes(cyl,mpg)) + geom_boxplot())
b <- ggplotly(ggplot(mtcars, aes(wt,mpg)) + geom_point())
subplot(a, b, nrows=1)
DT::datatable(mtcars, class = "cell-border stripe", rownames = FALSE, filter ="top",
editable =TRUE, extension = "Buttons", options = list(dom="Bfrtip",
buttons =c("copy", "csv", "excel", "pdf","print")))
ggplotly(ggplot(mtcars,aes(x=mpg)) + geom_histogram(binwidth=5))
# Display the date and time
# Similar to xvars above, this line is intended to demonstrate that text output
# won't be displayed in this RMarkdown example.
Sys.Date()
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
plot(pressure)
```
Since I need to process large datasets and generate graphs/plots and table I would prefer to keep them separately, so that my Rmarkdown doesn't crash. May be this is wrong and there could be a better approach, please suggest.
Many thanks for your time and help.

R, generate pretty plot by dfSummary

I have a problem using summarytools packet. There is tutorial:https://cran.r-project.org/web/packages/summarytools/vignettes/Introduction.html with pretty plots of data:
My problem is that my code generate only TEXT GRAPH. This is chunk of code in my markdown to generate plot:
```{r summary, results='markup'}
library(summarytools)
my_data <- ...
dfSummary(my_data)
```
Unfortunately it generates something like this:
How can I generate this pretty report using summarytools?
Or have you better tools for this? (generate graph, mean, std, etc.)
I found the correct syntax to generate plot:
print(dfSummary(baseline_train), method = 'render')
And the results look like this:
A little update on this:
Always use knitr chunk option results='asis', as someone pointed in an earlier comment.
It is possible to generate summaries including png graphs using print():
print(dfSummary(iris), method = "render")
Starting with version 0.9.0 (available only on GitHub as of Feb. 2019), markdown summaries will also include png graphs provided you specify the following arguments:
plain.ascii = FALSE
style = "grid"
a physical location for temporary png's (tmp.img.dir)
dfSummary(iris, plain.ascii = FALSE, style = "grid", tmp.img.dir = "/tmp")
Additionnal tips
In both cases, you will (in all likelihood) need to adjust the size of the graphs with dfSummary()'s graph.magnif parameter (try values between .75 and .85).
Exclude a column or two to avoid overly wide summaries:
dfSummary(iris, [...], varnumbers = FALSE, valid.col = FALSE)
You need to use results = 'asis' for the code chunk. Here is minimal reproducible example:
---
title: "Untitled"
output: html_document
---
```{r, results='asis'}
library(summarytools)
dfSummary(iris, plain.ascii = FALSE, style = "grid")
```
produces

Embeded Plots Missing when Knitting to PDF

I know this question has been asked in different formats, but when searching I couldn't find a solution or problem similar to mine.
Using Mac with RStudio (Version 1.0.153 ) R (version 3.4.3 (2017-11-30) -- "Kite-Eating Tree")
I am just trying to knit to a PDF (weave using knitr) in R markdown, but when I do, the plots are missing. When I knit to HTML the plots are there. I am using the earlywarnings package which helps create the plots. See example below using R markdown:
```{r, earlywarnings, fig.keep='all'}
library(earlywarnings)
data("foldbif")
x = foldbif
plot.ts(x)
```
That plot shows in the pdf output, but not when I create other plots like these:
```{r, echo=FALSE,results='hide',fig.keep='all', fig=TRUE}
out<-generic_ews(x,winsize=50,detrending="gaussian",
bandwidth=5,logtransform=FALSE,interpolate=FALSE)
```
or this one:
```{r, echo=FALSE, results='hide', fig.keep='all', fig=TRUE, warning=FALSE}
qda = qda_ews(x, param = NULL, winsize = 50, detrending = "gaussian",
bandwidth = NULL, boots = 100,s_level = 0.05, cutoff = 0.05,
detection.threshold = 0.002, grid.size = 50, logtransform = FALSE, interpolate = FALSE)
```
The last function also only displays 2 out of 3 plots, but I'll figure that out another time.
Any help would be appreciated. Please let me know if this was not clear.
I can confirm that the issue is related with the use of dev.new(). I copy-pasted the code of the function, removed it (the one line 136 of the function) and it worked, i.e. I get the figure on my pdf. There may be a way to call a function to avoid the effect of dev.new() that I am not aware of.

R Markdown: visNetWork not displayed in html output when using for loops (or functions)

My visNetwork is not displayed at all when the displaying is attempted in a for loop. In a regular R script, I use the print function and it works just fine, but it does not work in an R Markdown document.
Here is a (hopefully) reproducible example:
---
title: "I want my beautiful networks back!"
---
# First example that works
```{r}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
vn <- visNetwork(nodes, edges, width = "100%")
vn # Or print(vn)
```
# When does it not work?
## In a for loop
```{r}
for (i in 1) vn
```
## In a for loop + using print
This will display the network in the Viewer.
```{r}
for (i in 1) print(vn)
```
## And also in functions
Same remark...
```{r}
foo <- function(x) print(x)
foo(vn)
```
I'm using Rstudio version Version 1.1.383 and
here is the result of a sessionInfo()
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6
other attached packages:
[1] visNetwork_2.0.2
I just found a little workaround, consisting the following steps:
Save plot as HTML
Include the HTML code in RMD file
Here an example:
```{r}
for (i in 1:3){
visSave(vn, file = paste0("test",i,".html"))
}
```
```{r, results='asis'}
for (i in 1:3){
cat(htmltools::includeHTML(paste0("test",i,".html")))
}
```
Another solution is to use print(htmltools::tagList())
This prevents the !DOCTOOLS showing in the output.
```{r}
for (i in 1) print(htmltools::tagList(vn))
```
I came across the same issue / solution when working with Datatables and the solution was provided here by #Yihui: https://github.com/rstudio/DT/issues/67
Edit I've since realised that you need at least one visnetwork plotted outside of the loop, i.e. outside of print(htmltools::taglist()), otherwise the script to render is not added to the html file.
You can remove the !DOCTYPE by operating on the string.
cat (as.character(htmltools::includeHTML(paste0("vn",".html"))) %>%
{gsub("<!DOCTYPE html>","",.,fixed = TRUE)} %>%
{sub("\n","",.)}
)
I had the same problem but also wanted to knit my Rmd from the command line, not within RStudio, to easily generate reports for many different parameters, e.g.:
Rscript -e "rmarkdown::render('graphical-res-vis-reports.Rmd', \
params = list(tissue = '${tissue}'), \
output_file = sprintf('graphical-analysis-results_%s.html','${tissue}'))"
The htmltools::includeHTML(html_path) trick worked well when knitting from within RStudio, but it spat out a pandoc error when I tried to knit it from the command line because it's effectively concatenating multiple standalone HTMLs, which does not result in a valid HTML format. (EDIT: the pandoc error may have also been because R from the command line was using a much older version of pandoc than RStudio, but using iframes is still much cleaner.)
I finally found a solution using iframes that works well. Here is a minimal reproducible example:
---
title: "Finally, a way to print visNetworks in a loop!"
---
```{r make networks}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
html_list <- c()
for (i in 1:3){
vn <- visNetwork(nodes, edges)
outfile <- sprintf("vn_%s.html", i)
visSave(vn, file=outfile)
html_list <- c(html_list, outfile)
}
```
```{r plot networks, results="asis"}
for (i in html_list){
print(htmltools::tags$iframe(title = "My embedded document",
src = f, height = "650", width = "900", frameBorder = "0"))
}
```
EDIT: Note that changing the iframe height and width doesn't resize the object from the HTML file. However, you can increase the size of the visNetwork HTML object with a simple text replacement. In this example, I remove the whitespace padding and change the size from 960x500 to 960x960:
visSave(v1, file = out_html)
# adjust browser window size
cmd = sprintf('sed -i \'s|"browser":{"width":960,"height":500,"padding":40,"fill":false}|"browser":{"width":960,"height":960,"padding":0,"fill":false}|\' %s', out_html)
system(cmd)

Render rCharts in slides from Slidify

Recently I have been experimenting with slidify and rCharts. Tutorials for generating simple charts while using slidify are explanatory, but I was unable to find any such tutorial regarding rCharts.
For example, I know that the following generates an interactive plot
data(mtcars)
r1<- rPlot(mpg ~ wt | am + vs, data=mtcars, type="point")
data(iris)
hair_eye = as.data.frame(HairEyeColor)
rPlot(Freq ~ Hair | Eye,color = 'Eye', data = hair_eye, type = 'bar')
However, I have no idea how to incorporate the resulting plot into my slides using slidify.
EDIT - After the helpful comment
I tried the following, having seen it on Ramnath's git:
---
title : Practice
subtitle : makes perfect
author : Noob
job :
framework : io2012 # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : [nvd3] # {mathjax, quiz, bootstrap}
mode : selfcontained # {standalone, draft}
---
```{r setup, message = F, echo = F}
require(rCharts)
options(RCHART_WIDTH = 800, RCHART_HEIGHT = 500)
knitr::opts_chunk$set(comment = NA, results = 'asis', tidy = F, message = F)
```
## NVD3 Scatterplot
```{r echo = F}
data(mtcars)
n1 <- nPlot(mpg ~ wt, group = 'gear', data = mtcars, type = 'scatterChart')
n1$print('chart1')
```
But ended up with this error:
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
cannot open file 'libraries/widgets/nvd3/nvd3.html': No such file or directory
After which I decided to copy the nvd3 folder from Ramnath's widgets directly into mine, hoping that this would solve the matter. However, this ended up crazily showing Ramnath's git page as well as my slides in the background!
What to do? I would really appreciate any guidelines/pointers/advice on how to accomplish this task. And, I hope this question aids other novices like myself in using the wonderful rCharts.
Note: I am using the standard editor for R, not R-studio. I feel the former is less cluttered.
All instructions below assume that you have the dev branch of the packages installed (slidify, slidifyLibraries and rCharts). You can accomplish this using install_github.
pkgs <- c("slidify", "slidifyLibraries", "rCharts")
devtools::install_github(pkgs, "ramnathv", ref = "dev")
There are two ways to include an rCharts viz in your slidify document, and the deck below illustrates both ways. If you print a plot in a code chunk, as you would do so in the R console, slidify automatically detects that you are running it in a knitr session and as a result save the resulting html to an iframe and embed it in the deck. Alternately, you can specify the chart inline, in which case you have to use n1$show("inline") and also include ext_widgets: {rCharts: libraries/nvd3} in your YAML front matter.
The iframe method is the default and the recommended method to avoid conflicts between various javascript files and css. The inline method does work well for several rCharts libraries, but make sure to check before you use.
---
title : rCharts Integration
ext_widgets : {rCharts: libraries/nvd3}
mode: selfcontained
---
## NVD3 Plot Inline
```{r nvd3plot, results = 'asis', comment = NA, message = F, echo = F}
require(rCharts)
n1 <- nPlot(mpg ~ wt, data = mtcars, type = 'scatterChart')
n1$show('inline')
```
---
## NVD3 Plot Iframe
```{r nvd3plot2, results = 'asis', comment = NA, message = F, echo = F}
require(rCharts)
n1 <- nPlot(mpg ~ wt, data = mtcars, type = 'scatterChart')
n1
```

Resources