I am not sure it is the proper place for such a question. Eventually, tell me and I will delete it.
Imagine a colleague with limited technological competences. No competences on R at all. Is there a way or a command that allows to create an R Markdown html (with the Knitr package) output which accepts comments in the similar way of a text editor?
The matter has no mention on the website of R markdown http://rmarkdown.rstudio.com/ nor on of the Knitr package http://yihui.name/knitr/.
Not sure such functionality exists, but I could think about how this could be emulated
Abusing links, and have browser configuraion which shows link on hovering,
and maybe make such links in different color (linkcolor class?)
[MM](another bad idea)
Abusing R code, you'll get code rectangle with just a text
```{r, echo=TRUE, eval=FALSE}
MM: another bad idea
```
Abusing some R package which generates inlined HTML, say xtable
```{r results="asis", echo=FALSE}
comments.df <- data.frame(c("WHO", "MM"), c("CMT", "Another bad idea"))
print(xtable(comments.df), type = "html", include.rownames = FALSE)
```
Frankly, would be interested in the better answer, really good question...
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:
In bookdown how can I include R code within a custom block, whereby the R code will be parsed. Like in the example below the r code (plot function) will not be parsed. Is there a way to make this work?
```{block2 type='test'}
some text here
plot(1:10)
```
You can use text references as a hack. This seems to work as long as valid_markdown contains a single paragraph/line of markdown.
```{r}
valid_markdown <- your_function()
```
(ref:my_hack) `r valid_markdown`
```{block2, type="block"}
(ref:my_hack)
```
This hack works fine with text. Getting it work with plots will require a bit more work.
I want to center an image and/or text using R Markdown and knit a PDF report out of it.
I have tried using:
->Text<-
->![](image1.jpg)<-
That does not do the trick! Any other way of getting this done?
I had the same question. I have tried all solutions provided above and none of them worked... But I have found a solution that works for me, and hopefully for others too.
<center>
![your image caption](image.png)
</center>
This code will center both the image and the caption. It is essential that you leave lines between <center>, the image code, and </center>, otherwise the image will be centered but the caption will disappear.
If you want your image to have a clickable link, you can embed things like
[![your image caption](image.png)](www.link_to_image.com)
However, the caption will no longer appear.
So if you want a clickable caption you will have to do it in two steps:
<center>
![](image.png)
[your image caption](www.link_to_image.com)
</center>
Same here, make sure there are empty lines in between each command ones. If you want both the image and the caption to be clickable, then combine the middle and the last codes above. I hope this helps a bit.
If you are centering the output of an R code chunk, e.g., a plot, then you can use the fig.align option in knitr.
```{r fig.align="center"}
plot(mtcars)
```
You can use raw LaTeX in R Markdown. Try this:
\begin{center}
Text
\end{center}
There is, of course, a catch: everything between begin{...} and \end{...} is interpreted as raw LaTeX by Pandoc, so you can't use this technique to center the output of R code chunks, or Markdown content.
You can set the center (or other) alignment for the whole document as a Knitr option, using:
knitr::opts_chunk$set(echo = TRUE, fig.align="center")
None of the answers work for all output types the same way and others focus on figures plottet within the code chunk and not external images.
The include_graphics() function provides an easy solution. The only argument is the name of the file (with the relative path if it's in a subfolder). By setting echo to FALSE and fig.align=center you get the wished result.
```{r, echo=FALSE, fig.align='center'}
include_graphics("image.jpg")
```
I used the answer from Jonathan to google inserting images into LaTeX and if you would like to insert an image named image1.jpg and have it centered, your code might look like this in Rmarkdown
\begin{center}
\includegraphics{image1}
\end{center}
Keep in mind that LaTex is not asking for the file exention (.jpg). This question helped me get my answer. Thanks.
The simple solution given by Jonathan works with a modification to cheat Pandoc. Instead of direct Latex commands such as
\begin{center}
Text
\end{center}
you can define your own commands in the YAML header:
header-includes:
- \newcommand{\bcenter}{\begin{center}}
- \newcommand{\ecenter}{\end{center}}
And then you use:
\bcenter
Text and more
\ecenter
This works for me for centering a whole document with many code chunks and markdown commands in between.
I'm using beamer to knit pdf from Rmarkdown and what worked for me is:
\centering
![](image1.jpg)
If you know your format is PDF, then I don't see how the HTML tag
can be useful... It definitely does not seem to work for me. The other pure LaTeX solutions obviously work just fine. But the whole point of Markdown is not to do LaTeX but to allow for multiple format compilation I believe, including HTML.
Therefore, with this in mind, what works for me is a variation of Nicolas Hamilton's answer to Color Text Stackoverflow question:
#############
## CENTER TXT
ctrFmt = function(x){
if(out_type == 'latex' || out_type == 'beamer')
paste0("\\begin{center}\n", x, "\n\\end{center}")
else if(out_type == 'html')
paste0("<center>\n", x, "\n</center>")
else
x
}
I put this inside my initial setup chunk.
Then I use it very easily in my .rmd file:
`r ctrFmt("Centered text in html and pdf!")`
There is now a much better solution, a lot more elegant, based on fenced div, which have been implemented in pandoc, as explained here:
::: {.center data-latex=""}
Some text here...
:::
All you need to do is to change your css file accordingly. The following chunk for instance does the job:
```{cat, engine.opts = list(file = "style.css")}
.center {
text-align: center;
}
```
(Obviously, you can also directly type the content of the chunk into your .css file...).
The tex file includes the proper centering commands.
The crucial advantage of this method is that it allows writing markdown code inside the block.
In my previous answer, r ctrFmt("Centered **text** in html and pdf!") does not bold for the word "text", but it would if inside a fenced div.
For images, etc... the lua filter is available here
Just to update the question. To do this some easy way, you can add fig.align="center" to the chunk with the chuck knitr options:
knitr::opts_chunk$set(echo = TRUE,
fig.align="center" #align all the figures in the center
)
none of the answers worked but this
\newcommand{\bcenter}{\begin{center}}
\newcommand{\ecenter}{\end{center}}
but then the following problem is that it works for only one figure and then will not for any other figures.
I just started learning R I knew it was going to be difficult but what's worst is that there is little to no info that I can refer to.
None of these solutions worked for me when inserting a pdf figure in the text. After intensive trial and error, what made the trick for me (for a pdf output) was:
\hfil ![](image1.pdf) \hfil
Since the question asks for both text and image alignment and I had a hard time finding an option for text that worked, with non of the ones above working withing a code chunk (for me). I wanted to share this: it seem to do the trick to the best of it's abilities (meaning it's not perfectly centered but close)
centerText <- function() {
width <- getOption("width")
out <- "your text"
ws <- rep(" ", floor((width - nchar(out))/2))
cat(ws, out, sep = "")
}
centerText()
Original code comes from here
I'm writing an Rmd file, to be processed by knitr into HTML. It contains some R chunks that generate figures, which get stored as data URIs in HTML.
1) How do I add a caption to such an image? I'd like to have a caption that says something like "Figure 3: blah blah blah", where the "3" is automatically generated.
2) How do I later on reference this image, i.e., "as you can see in Figure 3, blah blah".
I'm late to the party, but I wanted to mention a small package I recently built to do figure captioning and cross-referencing with knitr. It is called kfigr and you can install it using devtools::install_github('mkoohafkan/kfigr'). It is still in active development but the main functionality is there. Be sure to check out the vignette, it shows some usage examples and defines some hooks for figure captions and anchors (I may later choose to have the package import knitr and define those hooks on load).
EDIT: kfigr is now available on CRAN!
You can create the figure numbers with a simple counter in R; see one example here. The problem is whether the markdown renderer will render the figure caption for you: R Markdown v1 won't, but v2 (based on Pandoc) will.
I do not know. There is no direct way to insert a label as an identifier for figures, so it is probably not possible to cross reference figures with pure Markdown. Once you've got issues like this, think (1) do I really need it? (2) if it is intended to be a document with a complicated structure, I think it is better to use LaTeX directly (Rnw documents).
Also very late to the party I changed Yihuis suggestion here that he also linked above to do referencing.
```{r functions, include=FALSE}
# A function for captioning and referencing images
fig <- local({
i <- 0
ref <- list()
list(
cap=function(refName, text) {
i <<- i + 1
ref[[refName]] <<- i
paste("Figure ", i, ": ", text, sep="")
},
ref=function(refName) {
ref[[refName]]
})
})
```
```{r cars, echo=FALSE, fig.cap=fig$cap("cars", "Here you see some interesting stuff about cars and such.")}
plot(cars)
```
What you always wanted to know about cars is shown in figure `r fig$ref("cars")`
One way to do both of these is described here: http://rmflight.github.io/posts/2012/10/papersinRmd.html
Another is described here (but I don't know if it does your #2). http://gforge.se/2014/01/fast-track-publishing-using-knitr-part-iii/
Another solution:
https://github.com/adletaw/captioner
From the README:
captioner() returns a captioner function for each set of figures, tables, etc. that you want to create. See the help files for more details.
For example:
> fig_nums <- captioner()
> fig_nums("my_pretty_figure", "my pretty figure's caption")
"Figure 1: my pretty figure's caption"
> fig_nums("my_pretty_figure", cite = TRUE)
I did both (figure numbers + references) with bookdown. I added in output section in the header of the file:
output:
bookdown::html_document2:
fig_caption : TRUE
Then I created a figure in a R code chunk like follows:
{r, my-fig-label,echo=F, eval=T, fig.align = 'center', fig.cap="This is my caption"}
knitr::include_graphics(here::here("images", "my_image.png"))
This produces an automatic number under your figure. You can refer to it with \#ref(fig:my-fig-label).
Using the official bookdown documentation 4.10 Numbered figure captions:
---
output: bookdown::html_document2
---
```{r cars, fig.cap = "An amazing plot"}
plot(cars)
```
```{r mtcars, fig.cap = "Another amazing plot"}
plot(mpg ~ hp, mtcars)
```
Sounds like it should be a common problem, but I didn't find an obvious trick.
Consider the knitr Rnw file below,
\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf, fig.align=center}
\begin{figure*}
<<aaa, fig.width=8, fig.height=5, fig.show=hold>>=
plot(1,1)
#
\end{figure*}
\end{document}
I would like this wide figure to span two columns, using a {figure*} LaTeX environment. Is there a hook for that?
EDIT: wrapping the chunk in figure* gives the following output.
Two facts:
knitr makes everything accessible for you, so LaTeX tricks are often unnecessary;
there is a chunk hook with which you can wrap your chunk results;
A simple-minded solutions is:
knit_hooks$set(chunk = function(x, options) {
sprintf('\\begin{figure*}\n%s\n\\end{figure*}', x)
})
I leave the rest of work to you to take care of more details in options (e.g. when options$fig.keep == 'none', you should not wrap the output in figure*). You may want to see how the default chunk hook for LaTeX is defined in knitr to know better how the chunk hook works.
However, in this case, I tend to write the LaTeX code by myself in the document instead of automatically creating it. After you have got figure*, you may start to think about \caption{} and \label{} (not hard, but I still want to see them in LaTeX).
Not sure about how knitr but for Sweave (and basic latex) there is in fact a trick: have the R code produce a pdf file, and then use standard \includegraphics to pull it in.
So with this:
\documentclass[twocolumn, 12pt]{article}
\usepackage{graphicx}
\begin{document}
%\SweaveOpts{dev=pdf}
<<aaa,fig=FALSE,print=FALSE,echo=FALSE>>=
pdf("mychart.pdf", width=6, height=3)
set.seed(42)
plot(cumsum(rnorm(100)), type='l', main="yet another random walk")
invisible(dev.off())
#
\begin{figure*}
\includegraphics{mychart.pdf}
\end{figure*}
\end{document}
I got the document below (which I then converted from pdf to png):
I also had a similar problem while preparing a figure that should span two columns in a IEEE two-column conference paper.
Setting the chunk hook caused some strange error in my setup.
Even this simple hook: knit_hooks$set(chunk = function(x, options) x)
But after looking into knitr::opts_chunk$get(), I realized that simply setting fig.env="figure*" solves the problem in an elegant way.
Here is how my chunk looks like in an Rnw file:
<<fig1, fig.width=18, fig.height=6, fig.env="figure*">>=
#