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
Related
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)
```
I have code similar to the following, which is dynamically generated and stored in a variable:
---
title: "test"
author: "me"
date: "3 June 2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, comment=""}
for (i in 1 : 3) {
cat('\n')
print(summary(iris[i*50 : 50, "Sepal.Length"] ))
}
```
Let's say it's stored in a variable named rmkdown_code
Now, I need to be able to execute the code in this variable and render it as html or pdf. I am aware of the results = asis options, and I've tried different variations of it. But still, I'm not able to get the above code to render in html. The html page comes up in rstudio, and it shows the contents of rmkdown_code variable. It's just not executing it.
I need the content of rmkdown_code to be rendered as though it was from a flat file.
I have tried the following, none of which worked. Some formatted the text better, but the graph is not plotted. I would like to avoid writing the content of the rmkdown_code variable to a flat file.
```{r,echo=FALSE,eval=TRUE}
knitr::knit_expand(text=rmkdown_code)
#eval(parse(text = rmkdown_code))
#eval(c(paste0("- `", rmkdown_code, "`"), sep = "\n"))
#eval(knitr::asis_output(rmkdown_code))
#res <- knitr::knit_expand(text=rmkdown_code);knitr::knit(text=res, quiet=F)
# knitr::inline_expr("2+2")
```
output of dput(rmarkdown):
## "---\ntitle: \"test\"\nauthor: \"me\"\ndate: \"3 June 2019\"\noutput: html_document\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n```{r, comment=\"\"}\nfor (i in 1 : 3) { \n cat('\\n') \n print(summary(iris[i*50 : 50, \"Sepal.Length\"] ))\n}\n```\n"
Here's a solution, not sure if it's ideal for your use case but it does successfully render rmkdown_code as an HTML report.
Be sure that you set your working directory or are working in a project, because the .rmd will render to your current wd.
rmkdown_code <- "---\ntitle: \"test\"\nauthor: \"me\"\ndate: \"3 June 2019\"\noutput: html_document\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n```{r, comment=\"\"}\nfor (i in 1 : 3) { \n cat('\\n') \n print(summary(iris[i*50 : 50, \"Sepal.Length\"] ))\n}\n```\n"
render_func <- function(x){
writeLines(x, "temp.rmd")
rmarkdown::render("temp.rmd")
}
render_func(rmkdown_code)
This gives us:
I have something like this in my R environment
myoutput <- xtable(mtcars)
and i want to see the updated myoutput in latex automatically, is this possible?
many thanks in advance,
You can use the texPreview package.
library(xtable)
library(texPreview)
LaTeX <- xtable(mtcars)
tex_preview(LaTeX)
This code displays the LaTeX table in the RStudio viewer.
If you are talking about somefile.rmd (or just create one in R Studio with this - .rmd - extension) then try the following:
---
title: "Somefile"
subtitle: "Somefile subtitle"
author: "Your Name"
output:
beamer_presentation:
slide_level: 2
pandoc_args: "--latex-engine=xelatex"
fig_width: 5
fig_height: 5
header-includes:
- \usepackage{tikz, graphicx, multirow, colortbl, schemabloc}
- \usepackage[11pt]{moresize}
- ... # something else
---
## Overview of someproject
```{r echo = FALSE, message = FALSE, warning = FALSE, fig.align = "center", ...}
d <-
read.csv2("somefile.csv", header = TRUE, sep = ";", dec = ".") %>%
head(.)
Using this code you do the following:
You create a beamer presentation (smth like ppt)
In the section between --- ... --- you set your "global configuration" of the presentation
Using ## you create a new slide
Using {r echo = FALSE, message = FALSE, ...} you can insert R code that will appear on that slide.
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).
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)
```