Your error is, that you want to execute the YAML header in a R script. When you use RStudio, then go to 'File' -> 'New File' -> 'R Markdown' and enter the YAML header and your code. Then you can render your RMD file via CTRL+Shift+K or in the console via rmarkdown::render("<path-to-your-file>").

If you do not use RStudio, save the script as a Rmd file (*.Rmd) file and render it via console.