'How to stop wrapfigure floating in rmarkdown to pdf

I have a RMarkdown document with some text, and I want to wrap the text around a figure. Now this hasn't been a problem previously using wrapfigure, however all of a sudden the image floats to the bottom of the document no matter what I try to do!

MWE that doesn't work for me:

---
title: "TEST"
date: "`r Sys.Date()`"
lang: "en"
output:
  pdf_document
fontsize: 10pt
header-includes:
- \usepackage{wrapfig}
- \usepackage{lipsum}
- \usepackage{mwe}
urlcolor: blue
---

\begin{wrapfigure}[H]{r}{0.5\textwidth}
  \includegraphics{example-image-a}
\end{wrapfigure}

# Header 1
\lipsum[1]
\lipsum[2]
\lipsum[3]

Here is a link to the result. I cannot attach images yet :/



Solution 1:[1]

The problem is that rmarkdown automatically loads the babel package with the bidi=default option as soon as any lang is specified in the header -- even if the language is English and definitely not written in any direction but from left to right. The bidi option makes zero sense in this case and will just cause trouble.

To avoid this, I suggest to remove the lang field in your header. The advantages of loading babel in an English document aren't terrible big (all the things like figure and table names are in English by default) and this avoids the problem with wrapfig...

(There is also a tiny syntax error in \begin{wrapfigure}[H]{r}{0.5\textwidth} -> The H is wrong, replace it by the number of lines the wrapfigure should span or leave it empty for wrapfig trying to guess the correct number automatically)

---
title: "TEST"
date: "`r Sys.Date()`"
output:
  pdf_document:
    keep_tex: true
fontsize: 10pt
header-includes:
- \usepackage{wrapfig}
- \usepackage{lipsum}
- \usepackage{mwe}
urlcolor: blue
---
# Header 1

\begin{wrapfigure}[]{r}{0.5\textwidth}
  \includegraphics{example-image-a}
\end{wrapfigure}
\lipsum[1]
\lipsum[2]
\lipsum[3]

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1