I'm not sure what the definitive approach is here (or even if there is one), but here's one option that should work:
First, create a separate text file (see image below for how to open a new text file in RStudio) and name it, say, my_header.tex.
Put the following in that file (source):
\usepackage{float}
\let\origfigure\figure
\let\endorigfigure\endfigure
\renewenvironment{figure}[1][2] {
\expandafter\origfigure\expandafter[H]
} {
\endorigfigure
}
These are the latex instructions that will result in the figures being placed where we want them.
Then in your rmarkdown file, include the following in the YAML header (the text at the top that's bounded at the top and bottom by ---).
output:
rmarkdown::pdf_document:
fig_caption: yes
includes:
in_header: my_header.tex
The in_header: my_header.tex puts the latex we just created into the preamble of the latex document that gets generated when you click Knit.
The code in your question isn't a reproducible rmarkdown document, so here is a sample document to work with:
---
title: With Latex Header File
output:
pdf_document:
fig_caption: yes
includes:
in_header: my_header.tex
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Here is a histogram of the poisson distribution:
```{r cars, fig.cap="my caption"}
hist(rpois(100,3))
```
The thing below is a table:
```{r}
knitr::kable(mtcars[1:5, 1:5], caption = "I need this to be the third thing that appears. But it comes out first???")
```
The thing below is a bigger table:
```{r}
knitr::kable(mtcars[1:6, 1:6], caption = "I need this to be the fourth thing that appears. But it comes out second???")
```
Here is a base graphics plot:
```{r pressure, echo=FALSE, fig.cap="Another caption"}
plot(pressure)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Below on the left is what the PDF output looks like with the rmarkdown document above. Below on the right is what the PDF output looks like if we change to the following YAML header:
---
title: Without Latex Header File
output:
pdf_document:
fig_caption: yes
---
As you can see, with the Latex Header File, the figures and tables are placed exactly where they are created in the rmarkdown document.