I am using bookdown in R. I have some sections I only want to appear in the HTML (gitbook) version (and not the PDF version).
I know about is_html_output(), but that doesn't appear to be what I want, and doesn't work except for very simple bits of text. So this works:
`r if (knitr:::is_html_output())'
## Some text {-}
Things to say to HTML readers.
'
`
But this doesn't (does not compile) because of the tick in don't :
`r if (knitr:::is_html_output())'
## Some text {-}
Things I don't want to say to PDF readers.
'
`
And any R code I wish to place in the chunk fails too.
So while I can use is_html_output(), it very much restricts what I can do.
Is there an easy way to have some text--whole sections, and other large amounts--only visible in the HTML version?
Seems simple... but I can't find a solution. Thanks for help.
P.
You may consider using child documents, e.g.,
```{r, child = if (knitr::is_html_output()) 'child.Rmd'}
Then you can write arbitrary content in child.Rmd.
Related
I guess my question is a potential if not probable duplicate of How to use inline R code in a bookdown theorem or example environment. It's been nearly 3 years since this question was asked, so a refresh might be welcome in any case, all the more given #YiHui's comment: "That is not possible with bookdown (at least for now)"?
Background: I am trying to use #YiHui bookdown package to produce a book with lecture slides (see creating accompanying slides for bookdown project). A key feature for this purpose is to be able to use conditional formatting, such as eval = (out_type=="beamer"). The issue I am facing is therefore to be able to add code chunks or inline R code inside bookdown custom environments (see https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html#theorems and https://bookdown.org/yihui/bookdown/custom-blocks.html). I would love to get the following to compile properly. Is there a solution? Would a hook work (see https://yihui.org/knitr/hooks/)? There is a hack that works for forcing pandoc to parse inside a latex environment, but i do no think it applies here. Would a lua filter work (I have no idea how to use this)?
En passant, I am also surprised to see $\digamma$ showing up properly in the html output, but not in the pdf output, though it is parsed correctly in the tex file. The amssymb package is loaded and it's supposedly defined in there - what am I missing?
Much appreciated any help on this. Here is a MWE - I just edited chapter 4 from the default bookdown project. You can simply replace the contents of the file 03-method.Rmd with the following:
# Methods
We describe our methods in this chapter.
So here is a theorem to prove 1+1 = `r 1+1`.
```{theorem, echo=TRUE}
we want to show that in R, 1+1 = 2.
We also wonder why `$\digamma$` ($\digamma$) not showing.
Shows in the html output only, not pdf.
But when I recompile the tex file produced by bookdown - shows up just fine!!
Indeed, is defined correctly from `\usepackage{amssymb}`.
```
```{proof, echo=TRUE}
- If I am not mistaken, I cannot get an Rmarkdown style list to work either in the proof environment.
- Well, this is where i would like to be able to use inline code.
- we use r to compute 1+1: `r 1+1`.
- Does not work.
- Just shows verbatim inline code.
```
With the current development version of bookdown:
remotes::install_github('rstudio/bookdown')
you can write theorems in Pandoc's fenced Divs, e.g.,
# Methods
We describe our methods in this chapter.
So here is a theorem to prove 1+1 = `r 1+1`.
::: {.theorem}
we want to show that in R, 1+1 = 2.
We also wonder why `$\digamma$` ($\digamma$) not showing.
Shows in the html output only, not pdf.
But when I recompile the tex file produced by bookdown - shows up just fine!!
Indeed, is defined correctly from `\usepackage{amssymb}`.
:::
::: {.proof}
- If I am not mistaken, I cannot get an Rmarkdown style list to work either in the proof environment.
- Well, this is where i would like to be able to use inline code.
- we use r to compute 1+1: `r 1+1`.
- Does not work.
- Just shows verbatim inline code.
:::
However, please note that this new syntax is not supported for beamer output yet.
I use the HTML and PDF outputs from bookdown as instructional material in a programming course, and I'd like to achieve the "page break" effect at the subsection level in addition to the chapter and section levels.
From what I have read in the bookdown documentation, "subsection" is not a permissible setting for the split_by argument in my bookdown's "_output.yaml" file.
bookdown::gitbook:
split_by: section
Is there a workaround besides creating individual books for each chapter (thus turning my current book-level subsections into chapter-level sections)? I strongly prefer having one book at the end.
A work around might be using "split_by: rmd"; see this answer for reference.
Then you put contents in each subsection into a separate Rmd file.
I tried this, and it works. The drawback is that I always receive this message when preview the book in Rstudio:
In split_chapters(output, gitbook_page, number_sections, split_by, :
You have 5 Rmd input file(s) but only 3 first-level heading(s). Did
you forget first-level headings in certain Rmd files?
Also, I don't know if there are other drawbacks.
I try to reference to a single footnote in a few places in the text. However, with the code below, I've got two footnotes with the same content.
---
title: "My document"
output: html_document
---
One part of the text [^1].
Two pages later [^1].
[^1]: My footnote
Is it possible to reference more than once to a specific footnote using rmarkdown?
I had the same problem. I used html tags which worked really well. Whatever you want as superscript just put between the <\sup> like below:
<sup> text </sup>
jan 6 2023 update:
now I use quarto which is eally easy as you can just use do[^1]
[^1]footnote text
My workaround here is to just do it manually using inline latex mathmode (e.g, \(^2\) ).. Annoying, but even if they had a solution, you'd have to remember the citation number anyways...
I would suggest you to go with latex solution if you do not have many footnotes per page. By latex solution I mean:
(in Markdown, use Latex to superscript the footnote number)
First part$^1$
(and the next one)
Second part$^2$
(at the end of your text add *** to create a line across the document)
(under the line, add the text below:)
1, 2: Text for your footnote
On the other hand, there is a thread created on this specific R-Markdown bug. Maybe take a look at it, in this link.
Hope I helped somehow.
I am trying to insert a pdf image into an r markdown file. I know it is possible to insert jpg or png images. I was just wondering if it is also possible to insert a pdf image. Thanks very much!
If you are just trying to insert an image that has been exported from, for example, some R analysis into a pdf image, you can also use the standard image options from the knitr engine.
With something like:
```{r, out.width="0.3\\linewidth", include=TRUE, fig.align="center", fig.cap=c("your caption"), echo=FALSE}
knitr::include_graphics("./images/imagename.pdf")
```
Unfortunately you can't specify the initial dimensions of your image output (fig.width and fig.height), which you would need to pre-define in your initial output, but you can specify the ultimate size of the image in your document (out.width). As noted below, however, this is limited to scaling down.
You could also of course leave out the initial directory specification if your files are in the same working directory. Just be aware of operating system differences in specifying the path to the image.
An alternative method is to use Markdown syntax noted by #hermestrismegistus on this post:
![Image Title](./path/to/image.pdf){width=65%}
This can also be collected for multiple images side-by side:
![Image Title](./path/to/image.pdf){width=33%}![Image2 Title](./path/to/image2.pdf){width=33%}![Image3 Title](./path/to/image3.pdf){width=33%}
Edit:
After working more extensively with in-text referencing, I have found that using r chunks and the include_graphics option to be most useful. Also because of the flexibility in terms of image alignment (justification).
As an example:
```{r image-ref-for-in-text, echo = FALSE, message=FALSE, fig.align='center', fig.cap='Some cool caption', out.width='0.75\\linewidth', fig.pos='H'}
knitr::include_graphics("./folder/folder/plot_file_name.pdf")
```
The reference can later be used in-text, for example, Figure \#ref(fig:image-ref-for-in-text) illustrates blah blah.
Some important things to note using this format:
You can only expand PDF images via a code chunk up to the out.width and out.height conditions set in the original .pdf file. So I would recommend setting them slightly on the larger side in your original image (just note that any chart text will scale accordingly).
The in-text reference code (in this case image-ref-for-in-text) CANNOT contain any underscores (_) but can contain dashes (-). You will know if you get this wrong by an error message stating ! Package caption Error: \caption outside float.
To stop your plots drifting to the wrong sections of your document, but in a way that unfortunately will generate some white space, the above example includes fig.pos='H'. Where H refers to "hold" position. The same can be achieved for the former Markdown option by placing a full-stop (period .) immediately after the last curly bracket.
Example:
![Image Title](./path/to/image.pdf){width=75%}.
Unfortunately, this latter option results in some unsightly full-stops. Another reason I prefer the include_graphics option.
Sorry, I found that there is a similar post before:
Add pdf file in Rmarkdown file
Basically, I can use something like below works well for the html output:
<img src="myFirstAlignment2.pdf" alt="some text" width="4200" height="4200">
And something like below works well for the pdf output:
(1)possible solution
\begin{center} <br>
\includegraphics[width=8in]{myFirstAlignment2.pdf} <br>
\end{center}
(2)possible solution
![Alt](myFirstAlignment2.pdf)
The myFirstAlignment2.pdf should be replaced with path\myFirstAlignment2.pdf if the pdf file is not in your working directory.
In relation to the comment of the best answer, there is a way to use the second option, and the output not come out tiny.
Use the following syntax below with the height being a large number. Having text in the brackets is necessary for it to work.
![Alt](./file.pdf){width=100% height=400}
None of the answers outlined worked well for me in terms of sizing the pdf, so adding another answer using the code chunk options for out.height and out.width to control the size:
```{r out.height = "460px", out.width='800px', echo=F}
knitr::include_graphics("./images/imagename.pdf")
```
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