R Markdown - SparkTables not rendering - r

I am trying to render a sparktable using Rmarkdown. But the output always comes out in raw html or tex format. This depends on whether I am rendering a PDF or an HTML. Not sure what to do here?
library(sparkTable)
data("AT_Soccer")
content <- list(
function(x) {sum(x)},
function(x) {round(sum(x),2)},
function(x) {round(sum(x), 2)},
newSparkLine(lineWidth = 2,pointWidth = 6),
newSparkBar()
)
names(content) <- c("Points","ShotGoal","GetGoal","GoalDiff","winLose")
vars <- c("points","shotgoal","getgoal","goaldiff","wl")
stab <- newSparkTable(AT_Soccer,content,vars)
export(stab, outputType = "html") ### For HTML R-Markdown files
export(stab, outputType = "tex") #### For PDF R-Markdown files
My output (for html files) looks like:
The pdf output is:
I am trying to get the actual sparktable. I have been able to render the actual table like this:
showSparkTable(stab)
However, that opens the spark table within the Shiny framework. I'm trying to produce multiple rmarkdown documents with spark tables.
I took this example from: https://journal.r-project.org/archive/2015-1/templ-kowarik-meindl.pdf. Page 29.
Solution for HTML
Setting this worked for me. Thanks to Martin. Still stuck on the pdf one though.
knitr::opts_chunk$set(results = 'asis')

After studying the documentation a bit I summarize what I learned about including sparkTables inside Rmd documents:
1. For HTML documents (outputType = 'html'):
Just as I said use the chunk option results = 'asis'.
2. For PDF documents (outputType = 'tex'):
You also need the option above in the case of PDF documents. BUT if you dont use it, you will see the plain LaTeX that is generated by export().
At the very bottom of that output you will find an important hint:
## Information: please do not forget to add the following command before \begin{document} in your tex-fi
##
## \newcommand{\graph}[3]{ \raisebox{-#1mm}{\includegraphics[height=#2em]{#3}}}
So what we have to do here is to
include that line of LateX in our preamble,
add results = 'asis' to the code chunk,
and set the argument infonote of export() to FALSE.
The last point prevents another error that the LaTeX compiler would throw (namely that we already have defined the command \graph).
What follows is a working example for a PDF document:
---
title: "Plotting Plots Under Code"
author: "Martin"
date: "February 1, 2017"
output: pdf_document
header-includes:
- \newcommand{\graph}[3]{ \raisebox{-#1mm}{\includegraphics[height=#2em]{#3}}}
---
```{r setup, echo = F, warning = F, message = F, results = 'asis'}
library(sparkTable)
data('AT_Soccer')
content <- list(
function(x) {sum(x)},
function(x) {round(sum(x), 2)},
function(x) {round(sum(x), 2)},
newSparkLine(lineWidth = 2, pointWidth = 6),
newSparkBar()
)
names(content) <- c('Points', 'ShotGoal', 'GetGoal', 'GoalDiff', 'winLose')
vars <- c('points', 'shotgoal', 'getgoal', 'goaldiff', 'wl')
stab <- newSparkTable(AT_Soccer, content, vars)
export(stab, outputType = 'tex', infonote = F)
```

Related

Pagedown package error in producing the output

I have recently decided to use pagedown package in producing pdf and html outputs and therefore installed the library. I am trying to run the very simple Rmd file that comes as default when I choose to use pagedown file as my new file in the RStudio.
Here is the Rmd file content if you would like to see;
---
title: "A Multi-page HTML Document"
author: "Yihui Xie and Romain Lesur"
date: "`r Sys.Date()`"
output:
pagedown::html_paged:
number_sections: FALSE
# uncomment this line to produce HTML and PDF in RStudio:
knit: pagedown::chrome_print
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction
This is an example of a multi-page HTML document with some options shown in YAML header. See https://pagedown.rbind.io for the full documentation. The rest of this document is random text.
# Random text
```{r, results='asis', echo = FALSE}
random_markdown = function(len = 100) {
uri = knitr::image_uri(file.path(R.home('doc'), 'html', 'logo.jpg'))
text = function(len) {
trimws(paste(sample(c(letters, rep(' ', 10)), len, TRUE), collapse = ''))
}
id = function() paste(sample(letters, 8, TRUE), collapse = '')
figure = function(i = id()) {
sprintf('![(#fig:%s)The R logo.](%s){width=%d%%}', i, uri, sample(20:60, 1))
}
tab = paste(knitr::kable(head(mtcars[, 1:5])), collapse = '\n')
table = function(i = id()) {
c(sprintf('Table: (#tab:%s)A table example.', i), tab)
}
unlist(lapply(seq_len(len), function(i) {
if (i %% 20 == 0) return(paste('#', text(sample(10:30, 1))))
if (i %% 10 == 0) return(paste('##', text(sample(10:30, 1))))
# insure some elements
if (i == 3) return(text(50))
if (i == 4) return(figure("md-fig"))
if (i == 5) return(text(50))
if (i == 6) return(table("md-tab"))
# then random
type = sample(1:3, 1, prob = c(.9, .03, .07))
switch(type, text(sample(50:300, 1)), figure(), table())
}))
}
cat(random_markdown(), sep = '\n\n')
# Knitr inserted Figures and tables
## Simple graphics
```
Until here, R markdown can run the document well. However, when I tried to add the following two code chunks, the document fails to run.
``` {r simple-graphic, fig.cap = 'A very simple plot'}
plot(1)
```
## Simple tables
```{r simple-table}
knitr::kable(head(mtcars, 3), caption = "A Simple table")
```
And here is the error I get;
Error in force(expr) : Failed to generate output in 30 seconds (timeout).
Calls: <Anonymous> -> with_temp_loop_maybe -> with_loop -> force
Closing websocket connection
Closing browser
Cleaning browser working directory
Closing local webserver
I do not understand why the document does not fail to run in the first phase, while it fails to run in the second step. I tried to find a solution through web. I hope I am clear regarding my problem and I look forward to your reply. Thank you for your understanding beforehand.
If you just remove knit: pagedown::chrome_print the document will render to HTML just fine, Then from here, you can "print to PDF" from the browser to get both an HTML and a PDF doc of the output
---
title: "A Multi-page HTML Document"
author: "Yihui Xie and Romain Lesur"
date: "`r Sys.Date()`"
output:
pagedown::html_paged:
number_sections: FALSE
---
I think the issue might be your are specifying 2 different output formats, and Rmarkdown is taking a long time to render these
There is a similar issue discussed here the advice was to increase the timeout value, as it's default is 30 seconds until the process is fails out. and another similar issue here... but to be honest, I was not able to correct apply the timeout argument in chrome_print

How to reproducibly include R code in Word documents with Rmarkdown?

I have some R code in a package. I don't want to copy that code, but I want to display it in a pretty way in Word with syntax highlighting without any manual steps.
I looked at styler::style_text in combination of capture.output and that looks nice in the browser, but all the formatting is lost when knitting to Word. Is there some way to preserve it? I'm thinking the best thing would be to have Word native styling but the next best (acceptable) thing would be to somehow render the output to an image and include that. Has anyone done these things to document their code in a report?
show_code = function (fun) {
stopifnot(is.function(fun))
out = capture.output(fun)
n = length(out)
without_bytecode_and_env_lines = -1*c(n-1, n)
code = paste(out[without_bytecode_and_env_lines], collapse = "\n")
styler::style_text(code)
}
I believe you are trying to use syntax highlighting on the output of show_code and to do that, you simply need to use the options comment="" and class.output="r" and syntax highlighting will apply to the output.
---
title: "Source Code highlighting"
output:
word_document:
highlight: kate
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
```{r echo=FALSE}
show_code = function (fun) {
stopifnot(is.function(fun))
out = capture.output(fun)
n = length(out)
without_bytecode_and_env_lines = c(n-1, n)
code = paste0(out[-without_bytecode_and_env_lines], collapse = "\n")
styler::style_text(code)
}
```
### The source code for `lm`
```{r comment='', echo=FALSE, class.output = "r"}
show_code(lm)
```

Print an R help file vignette as output into an R HTML notebook

I'm trying to print an R help file vignette in an R notebook chunk for output into an HTML file. I want the entire vignette to show up as output in the HTML notebook preview because it serves as a nice data dictionary for a quick regression example. Using library(mlbench), I tried:
print(?BostonHousing2)
and I tried just calling
?BostonHousing2
in the code chunks, and neither of them output to the HTML file, they just populate in the Help tab inside of RStudio.
Anyone have any ideas?
Here is a way (if I correctly understand what you want). But maybe not the best one.
---
title: "Untitled"
author: "Stéphane Laurent"
date: "29 février 2020"
output: html_document
---
```{r setup, include=FALSE}
library(gbRd) # for Rd_fun
```
```{r, results='asis'}
Rd <- Rd_fun(help("pretty"))
htmlfile <- tempfile(fileext = ".html")
tools::Rd2HTML(Rd, htmlfile, package = "",
stages = c("install", "render"))
htmllines <- readLines(htmlfile)
i <- grep("<body>", htmllines)
j <- grep("</body>", htmllines)
cat(htmllines[(i+1):(j-1)], sep = "\n")
```
Based on Noam Ross's solution, and modified with some of the code in Stéphane Laurent's answer, the following function can be used to return an HTML version of the help file
help_console <- function(topic, package,
format=c("text", "html", "latex", "Rd"),
before=NULL, after=NULL) {
# topic - the command for which help is required
# package - the package name with the required topic
# format - output format
# before - place code before the output e.g. "<blockquote>"
# after - place code after the output e.g. "</blockquote>"
# based on code by Noam Ross
# http://www.noamross.net/archives/2013-06-18-helpconsoleexample/
# Stéphane Laurent
# https://stackoverflow.com/questions/60468080/
# print-an-r-help-file-vignette-as-output-into-an-r-html-notebook
# and Michael Sumner (mdsumner)
# https://stackoverflow.com/questions/7495685/
# how-to-access-the-help-documentation-rd-source-files-in-r
format <- match.arg(format)
if (!is.character(topic)) topic <- deparse(substitute(topic))
db <- tools::Rd_db(package)
helpfile <- db[paste0(topic, ".Rd")][[1]]
hs <- capture.output(
switch(
format,
text = tools::Rd2txt(helpfile),
html = tools::Rd2HTML(
helpfile,
package = "",
stages = c("install", "render")
),
latex = tools::Rd2latex(helpfile),
Rd = tools:::prepare_Rd(helpfile)
)
)
if (format == "html") {
i <- grep("<body>", hs)
j <- grep("</body>", hs)
hs <- hs[(i+1):(j-1)]
}
hs <- c(before, hs, after)
hs <- cat(hs, sep = "\n")
invisible(hs)
}
Which then can be used as follow in a RMarkdown document, ready for knitting:
```{r, echo = FALSE, results = "asis"}
help_console("pretty", "base", format = "html")
```
As usual, the R chunk needs to be set to results = "asis" to output to HTML.
This solution does not require the gbRd package.
For some strange reason, I can Knit to html_vignette from RStudio's Knit dropdown, but cannot successfully Build Document from the RStudio menu with Project Options - Build Tools - Roxygen Configure - Vignettes enabled, with the error
Error: Sections \title, and \name must exist and be unique in Rd files
thrown when trying to use the help_console function.
However, I was able to successfully able to create the HTML vignette and incorporate into a package with A-breeze's solution, or building a source or binary package (building source/binary packages can be done from RStudio's "build" menu).

How to generate a graph html widget for apriori rules visulization within rmarkdown compiler with a for loop with R?

I've been trying to generate a sequence of graph plots inside rmarkdown html compiler...
```{r, include=T, echo=F, fig.height=4, fig.width=10,warning=FALSE}
Here direct is the directory where the files are listed from
"files" is the list of files objects in the transaction form needed for the read.transaction function argument
direct <- "......"
files <- list.files(path = ".....")
for (i in 1:length(files)) {
tr<-read.transactions(file = paste(as.character(direct),"/",files[i],sep = ""),format = "basket",sep = ",")
rules <- apriori(tr, parameter = list(supp=sup, conf=confid))
rules <- sort(rules, by='count', decreasing = TRUE)
plotr <- plot(rules, method = "graph", engine = "htmlwidget")
}
```
I have tried print(plotr), printing just plot(rules,...) and nothing seems to work.
The problem is when I knit the markdown, the plot of the different transaction files doesn't pop up in the html generated by the .Rmd file. Consider that this loop is inside a function that runs inside the chunk.
It would be nice if someone could help me try to solve this problem. If its worth for something, I am trying to generate a report that returns different plot rules based on the apriori algorithm applied to the different files.
If anyone has any idea how this could be solved would be a great help, thank you.
To put multiple htmlWidgets in one RMarkdown chunk you need to create a taglist. Here is an example:
---
title: "Example RMarkdown with multiple arulesViz htmlWidgets in one chunk"
output: html_document
---
```{r}
library(arulesViz)
data(Groceries)
rules <- apriori(Groceries, parameter=list(support=0.001, confidence=0.8))
widget_list <- lapply(1:10, FUN = function(i)
plot(sample(rules, size = 10), method = "graph", engine = "htmlwidget"))
htmltools::tagList(widget_list)
```
You can also use a regular loop to populate the list. More information on this issue can be found at https://github.com/rstudio/DT/issues/67
To hide the messages from library and apriori in the resulting document you can do this:
---
title: "Example RMarkdown with multiple arulesViz htmlWidgets in one chunk"
output: html_document
---
<!-- Hide the messages for library -->
```{r, echo = FALSE, results = FALSE, warning = FALSE, message = FALSE}
library(arulesViz)
```
<!-- verbose = FALSE hides the progress report for apriori -->
```{r}
library(arulesViz)
data(Groceries)
rules <- apriori(Groceries, parameter=list(support=0.001, confidence=0.8),
control = list(verbose = FALSE))
widget_list <- lapply(1:10, FUN = function(i)
plot(sample(rules, size = 10), method = "graph", engine = "htmlwidget"))
htmltools::tagList(widget_list)
```

Rmarkdown Chunk Name from Variable

How can I use a variable as the chunk name? I have a child document which gets called a number of times, and I need to advance the chunk labels in such a manner than I can also cross reference them.
Something like this:
child.Rmd
```{r }
if(!exists('existing')) existing <- 0
existing = existing + 1
myChunk <- sprintf("myChunk-%s",existing)
```
## Analysis Routine `r existing`
```{r myChunk,echo = FALSE}
#DO SOMETHING, LIKE PLOT
```
master.Rmd
# Analysis Routines
Analysis for this can be seen in figures \ref{myChunk-1}, \ref{myChunk-2} and \ref{myChunk-3}
```{r child = 'child.Rmd'}
```
```{r child = 'child.Rmd'}
```
```{r child = 'child.Rmd'}
```
EDIT POTENTIAL SOLUTION
Here is one potential workaround, inspired by SQL injection of all things...
child.Rmd
```{r }
if(!exists('existing')) existing <- 0
existing = existing + 1
myChunk <- sprintf("myChunk-%s",existing)
```
## Analysis Routine `r existing`
```{r myChunk,echo = FALSE,fig.cap=sprintf("The Caption}\\label{%s",myChunk)}
#DO SOMETHING, LIKE PLOT
```
A suggestion to preknit the Rmd file into another Rmd file before knitting&rendering as follows
master.Rmd:
# Analysis Routines
Analysis for this can be seen in figures `r paste(paste0("\\ref{", CHUNK_NAME, 1:NUM_CHUNKS, "}"), collapse=", ")`
###
rmdTxt <- unlist(lapply(1:NUM_CHUNKS, function(n) {
c(paste0("## Analysis Routine ", n),
paste0("```{r ",CHUNK_NAME, n, ", child = 'child.Rmd'}"),
"```")
}))
writeLines(rmdTxt)
###
child.Rmd:
```{r,echo = FALSE}
plot(rnorm(100))
```
To knit & render the Rmd:
devtools::install_github("chinsoon12/PreKnitPostHTMLRender")
library(PreKnitPostHTMLRender) #requires version >= 0.1.1
NUM_CHUNKS <- 5
CHUNK_NAME <- "myChunk-"
preknit_knit_render_postrender("master.Rmd", "test__test.html")
Hope it helps. Cheers!
If you're getting to this level of complexity, I suggest you look at the brew package.
That provides a templating engine where you can dynamically create the Rmd for knitting.
You get to reference R variables in the outer brew environment, and build you dynamic Rmd from there.
Dynamic chunk names are possible with knitr::knit_expand(). Arguments are referenced in the child document, including in the chunk headers, using {{arg_name}}.
So my parent doc contains:
```{r child_include, results = "asis"}
###
# Generate a section for each dataset
###
species <- c("a", "b")
out <- lapply(species, function(sp) knitr::knit_expand("child.Rmd"))
res = knitr::knit_child(text = unlist(out), quiet = TRUE)
cat(res, sep = "\n")
```
And my child doc, which has no YAML header, contains:
# EDA for species {{sp}}
```{r getname-{{sp}}}
paste("The species is", "{{sp}}")
```
See here in the RMarkdown cookbook.

Resources