I'm using the RStudio IDE (v 0.99.323) with rmarkdown and am attempting to produce model tables via knitr using htmlreg to produce MSWord output. Suspect I've missed something simple.
The rmarkdown chunk appended below creates a separate word file 'mytable.doc' with a beautiful table. However, when I click 'Knit Word' in the RStudio IDE, the line htmlreg(m) generates html table code in the MSWord document. What am I doing wrong?
Many thanks! --Dale
```{r, results='asis'}
library(MASS)
library(texreg)
data(menarche)
m <- glm(cbind(Menarche, Total-Menarche) ~ Age, family=binomial(logit), data=menarche)
htmlreg(m, file = "mytable.doc", caption="Age at Menarche", inline.css = TRUE, doctype = TRUE, html.tag = TRUE, head.tag = TRUE, body.tag = TRUE, ci.force=TRUE, ci.test=NULL,bold=TRUE)
htmlreg(m)
```
Try this in your chunk, still using result='asis':
library(pander)
pander(m)
Hat tip to http://www.r-statistics.com/2013/03/write-ms-word-document-using-r-with-as-little-overhead-as-possible/
They also suggest a nice way to clarify code chunks so that you can just call print(m) and the output in markdown will call the appropriate function from pander.
Can you please try the latest texreg version 1.34.2 (see the .tar.gz file here or in this post)?
According to the RStudio developers, the problem is that they switched to a newer version of Pandoc, which does not work with indented HTML code anymore. More precisely, it interprets text that was indented with four spaces as a code block, as in Markdown notation. See here for their problem description.
So in the new texreg version, there is a new argument called indentation = "" in the htmlreg function. It switches indentation off by default. Using indentation = " " restores the previous behavior.
Edit 1: Please also make sure to use arguments center = FALSE and star.symbol = "\\*" for alignment on the left and for displaying significance stars correctly. Asterisks need to be escaped because they are otherwise interpreted as part of the Markdown syntax:
```{r, results = 'asis'}
htmlreg(m, center = FALSE, star.symbol = "\\*")
```{r}
For PDF notebooks (which use LaTeX internally), use texreg:
```{r, results = 'asis'}
texreg(m, float.pos = "h")
```{r}
Edit 2: Also read the help page of htmlreg, especially the part where the arguments of htmlreg are described. They contain some useful information on how to make the documents as compatible as possible with Markdown, which is used by RStudio, Pandoc, and knitr to create HTML documents. In particular, use arguments inline.css = TRUE, doctype = FALSE, html.tag = FALSE, head.tag = FALSE, and body.tag = FALSE when you do not intend to create a full-fledged HTML document.
About MS Word: You mentioned in a comment below your question that you wanted to create either HTML or Word documents. The htmlreg function is intended to create HTML files, not Word files (as the name of the function implies). It is possible to load these HTML files in MS Word, though, because Word is able to interpret HTML code. However, knitr creates binary Word documents, and embedding HTML code directly in these binary Word documents is not possible, as far as I know (but I may be wrong because I don't know how knitr creates the Word files internally). You could, however, try to create HTML notebooks, save them to disk, and then open them in MS Word.
This is a problem of pandoc markdown, or of htmlreg not creating the correct indentation. I do not fully understand if this is a bug or a feature because of the cryptic:
http://rmarkdown.rstudio.com/authoring_pandoc_markdown.html#raw-html
Try a simple .md (not .rmd) file as follows:
<h1>Works</h1>
<table border="8">
<tr>
<td>111</td>
<td>222</td>
<td>444</td>
</tr>
</table>
<h1>Not what you want</h1>
<table border="8">
<tr>
<td>111</td>
<td>222</td>
<td>444</td>
</tr>
</table>
<h1>Works too (not in screenshot)</h1>
<table border="8">
<tr><td>111</td><td>222</td><td>444</td></tr>
</table>
The package author has updated texreg to switch-off indentation by default.
See:
http://rmarkdown.rstudio.com/authoring_migrating_from_v1.html#preserving-generated-html
after updating the package via:
install.packages("texreg", repos = "http://R-Forge.R-project.org")
The chunk below placed in an rmarkdown (.Rmd) document now produces a beautiful html table when I 'Knit HTML' within RStudio. However, 'Knit Word' still does not produce the expected output.
```{r, results='asis'}
library(texreg)
htmlreg(m, caption="Age at Menarche", caption.above=TRUE, ci.force=TRUE, ci.test=NULL,bold=TRUE)
```
Related
I'm trying to embed a static image of a targets workflow in an rmarkdown document. I tried to do this by using tar_mermaid, defining a target that writes the workflow in mermaid format mm <- tar_mermaid(); writeLines(mm, "target_mermaid.js") but the help for tar_mermaid says
You can visualize the graph by copying
the text into a public online mermaid.js editor or a mermaid GitHub code chunk
I am looking for a programmatic way to either (1) embed the Javascript output in an (R)markdown file, or (2) render it (as SVG, PNG, whatever).
I thought as a shortcut that I could cut-and-paste into a markdown code chunk delimited by ```mermaid, or use cat(readLines("target_mermaid.js"), sep = "\n") in a chunk with results = "asis" but I guess that only works in Github markdown (I'm using Pandoc to render to HTML) ... ?
The visNetwork package has a visSave() function which can save to HTML (not quite what I wanted but better than what I've managed so far), and a visExport() function (which saves to PNG etc. but only by clicking in a web browser). Furthermore, targets wraps the visNetwork functions in a way that is (so far) hard for me to unravel (i.e., it doesn't return a visNetwork object, but automatically returns a widget ...)
For the time being I can go to https://mermaid.live, paste in the mermaid code, and export the PNG manually but I really want to do it programmatically (i.e. as part of my workflow, without manual steps involved).
I am not quite sure about the answer. But I have an idea. And I will delete if it is not adequate:
If you want execute mermaid code to get for example an html output then you could do this with quarto. I am not sure if this is possible with rmarkdown:
See https://quarto.org/docs/authoring/diagrams.htmlS
---
title: "Untitled"
format: html
editor: visual
---
## Quarto
Quarto enables you to weave together content and executable code into a finished document. To learn more about Quarto see <https://quarto.org>.
## Running Code
```{mermaid}
flowchart LR
A[Hard edge] --> B(Round edge)
B --> C{Decision}
C --> D[Result one]
C --> E[Result two]
```
output:
#landau's suggestion to look here almost works, if I'm willing to use Quarto instead of Rmarkdown (GH Markdown is not an option). The cat() trick was the main thing I was missing. The .qmd file below gets most of the way there but has the following (cosmetic) issues:
I don't know how to suppress the tidyverse startup messages, because targets is running the visualization code in a separate R instance that the user has (AFAIK) little control of;
the default size of the graph is ugly.
Any further advice would be welcome ...
---
title: "targets/quarto/mermaid example"
---
```{r}
suppressPackageStartupMessages(library("tidyverse"))
library("targets")
```
```{r, results = "asis", echo = FALSE}
cat(c("```{mermaid}", tar_mermaid(), "```"), sep = "\n")
```
Beginning of document:
Zooming out:
I have created a large R Markdown document with many child docs using RStudio to produce output in both HTML and PDF.
I added this simple line to the YAML parameters of the document and it does exactly what I need. The entire doc is rendered and saved as both html and pdf output. Formatting of complex tables is preserved nicely.
knit: pagedown::chrome_print
BUT - the pdf is oversized. It simply needs to be scaled to 0.8 to be really useable. chrome_print documentation says that scale can be adjusted within the chrome_print command. I've tried this:
knit: pagedown::chrome_print(scale = 0.8)
which produces an Execution Halted error. I have tested other ways to pass parameters through the render to chrome_print, but none work.
The question is simple: Is there a way to pass parameters into the knit: pagedown::chrome_print operation?
After much experimentation, I find there is currently no way to adjust any pdf options from within R markdown YAML using knit: pagedown::chrome_print.
The workaround I've found is to use the code chunk below to render the Rmarkdown. It saves to both html and pdf formats and allows the user to assign filenames. Note that scaling does not adjust pagination nicely without CSS reset as shown. This works great, and allows full use of rmarkdown parameters and all chrome_print options.
fname = "OutputFilename"
pagedown::chrome_print(
rmarkdown::render(
input = "input.Rmd",
output_file = paste0(fname, ".html"),
output = paste0(fname, ".pdf"),
options = list(scale = 0.7, preferCSSPageSize = FALSE))
I tried to use pander tables in a markdown page that is generated from R-markdown files like Yihui describes in an example page.
In my _config.yml I have the markdown type set to markdown: kramdown. I know that some things are different in this markdown type compared to the markdown knitr uses per default. So if I compile my page in RStudio with knitr the table looks alright. If I compile the page with jekyll the table looks not formatted right.
```{r key}
library(pander)
LETTERSplus <- c(LETTERS, "_", ".", ",", "-")
key <- sample(LETTERSplus)
names(key) <- LETTERSplus
pander(key)
```
Compiled with knitr inside RStudio it looks alright:
Compiled with Jekyll it looks like this:
I don't want to use kable since it formats the table differently and there is now column wrap if the table is too long.
Do I have to set some special pandoc options to make this work? Options to define the markup type pandoc has to output? I don't see any other options inside the pander() function.
I know this question is similar to this one. But I couldn't get a solution there so posting it here again.
I want to get the exact same output as I get by clicking "Knit HTML" but via a command. I tryied using knit2html but it messes with the formatting and does not include the title, kable does not work etc.
Example:
This is my test.Rmd file,
---
title: "test"
output: html_document
---
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(knitr,quietly=T)
kable(summary(cars))
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Output:
Knit HTML
knit2html
The documentation tells us:
If you are not using RStudio then you simply need to call the rmarkdown::render function, for example:
rmarkdown::render("input.Rmd")
Note that in the case using the “Knit” button in RStudio the basic mechanism is the same (RStudio calls the rmarkdown::render function under the hood).
In essence, rmarkdown::render does a lot more setup than knitr::knit2html, although I don’t have an exhaustive list of all differences.
The most flexible way of rendering the output is, at any rate, to supply your own stylesheet to format the output according to your wishes.
Please note that you need to set up Pandoc manually to work with rmarkdown::render on the command line.
That said, here are two remarks that would improve the knitr::knit2hmtl output, and that are superior to using rmarkdown::render in my opinion:
To include the title, use a Markdown title tag, not a YAML tag:
# My title
To format tables, don’t use the raw kable function. In fact, this is also true when using rmarkdown::render: the alignment of the table cells is completely off. Rmarkdown apparently uses centering as the default alignment but this option is almost never correct. Instead, you should left-align text and (generally) right-align numbers. As of this writing, Knitr cannot do this automatically (as far as I know) but it’s fairly easy to include a filter to do this for you:
```{r echo=FALSE}
library(pander)
# Use this option if you don’t want tables to be split
panderOptions('table.split.table', Inf)
# Auto-adjust the table column alignment depending on data type.
alignment = function (...) UseMethod('alignment')
alignment.default = function (...) 'left'
alignment.integer = function (...) 'right'
alignment.numeric = function (...) 'right'
# Enable automatic table reformatting.
opts_chunk$set(render = function (object, ...) {
if (is.data.frame(object) ||
is.matrix(object)) {
# Replicate pander’s behaviour concerning row names
rn = rownames(object)
justify = c(if (is.null(rn) || length(rn) == 0 ||
(rn == 1 : nrow(object))) NULL else 'left',
sapply(object, alignment))
pander(object, style = 'rmarkdown', justify = justify)
}
else if (isS4(object))
show(object)
else
print(object)
})
```
I am currently writing a documentation for an R package hosted on GitHub. I use knitr along with R Markdown to write the README file. Hitting the 'Knit HTML' button in RStudio produces an HTML like I would expect it.
However, pushing README.rmd to GitHub results in what you see in the lower page section when following the above link. For example, the topmost code chunk is declared as follows in the README.rmd file:
```{r global_options, include = FALSE}
library(knitr)
options(width = 120)
opts_chunk$set(fig.width = 12, fig.height = 8, fig.path = 'Figs/',
include = TRUE, warning = FALSE, message = FALSE)
```
However, the include = FALSE statement in the first line of code is simply ignored in this case, and the piece of code that was supposed to be hidden is displayed on the referring GitHub page. In addition, results (e.g. from plot(), head()) are not visualized although opts_chunk$set(..., include = TRUE).
Did anyone encounter a similar problem and can me help me get my README document displayed correct, i.e. in the way RStudio would handle it, on GitHub?
The readme file you are trying to publish on github should be a plain markdown document i.e., a .md file and not the raw .rmd. So first you knit the .rmd with knitr (within R) as follows:
knit(input="readme.rmd", output = "readme.md") #see ?knit for more options
That will evaluate the global and chunk options specified in the source .rmd and produce a .md that's formatted accordingly and which github can render readily.
For more information on using an .Rmd to generate the .md see the Readme.Rmd section of http://r-pkgs.had.co.nz/release.html
You can also have devtools set up this automatically for your package using devtools::use_readme_rmd().