How to hold figure position with figure caption in pdf output of knitr?

For me adding the float package and then \floatplacement{figure}{H} in YAML solved the issue like :

---
title: "test"
date: "`r Sys.Date()`"
output: 
  pdf_document :
    keep_tex: true
    number_sections: true
header-includes:
 \usepackage{booktabs}
 \usepackage{longtable}
 \usepackage{array}
 \usepackage{multirow}
 \usepackage[table]{xcolor}
 \usepackage{wrapfig}
 \usepackage{float}
 \floatplacement{figure}{H}
---

As Andrew pointed out, this fig.pos doesn't work in chunks, but it does work if it is put in global options:

```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.pos = 'H')
```

EDIT: the above apparently used to work and needs \usepackage{float} in the preamble:

header-includes:
 \usepackage{float}

See also here and the Cookbook for some other ways.


Update look at this better solution here. (the summary of the problem below is still good, but follow the link to a better solution).

To summarise some testing in RStudio

The knitr chunk argument fig.pos = "H" works as long as fig_caption: yes is not in the yaml header.

Each figure in the generated .tex looks like this

\subsection{my_section}\label{my_section}

\includegraphics{path_to_fig.pdf}

But if fig_caption: yes is in the yaml header then the .tex looks like this

\subsection{my_section}\label{my_section}

\begin{figure}[htbp]
\centering
\includegraphics{path_to_fig.pdf}
\caption{}
\end{figure}

fig.pos = "H" has not been used, "htbp" is there instead.

A workaround for this using RStudio:

put

fig_caption: yes
keep_tex: yes

in the yaml as well as

header-includes: \usepackage{float}

then search and replace [htbp] with [H] in the generated .tex file

then open the .tex file in RStudio and use the "Compile PDF" button.


Example .Rmd

---
title: "Testing fig placement with captions"
author: "Andrew Dolman"
date: "1 September 2015"
output: 
  pdf_document: 
    fig_caption: yes
    keep_tex: yes
header-includes: \usepackage{float}
---

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}
summary(cars)
```

You can also embed plots, for example:

```{r, echo=FALSE, fig.pos="H"}
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.

```{r, echo=FALSE, fig.pos="H"}
plot(cars)
```