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.