I just figured out how to do this while trying to add google analytics to my own RMD site on Github pages.
To add the Google Analytics code before the closing </head> html document created using RMD ...
Step 1: Create an .html file containing Google Analytics Script and save it in the working directory of your site. (Just create a new text file, paste Script, save the file filename.html.
Step 2: Adjust the yaml header of your rmd file to include the arguments include: and in_header:, as well as a link to the .html file containing the tracking code
--- title: "" output: html_document: includes: in_header: GA_Script.html ---
Step 3: Adjust the yaml headers for each rmd file associated with your site so that each page returns to Google Analytics.
It is recommended that the Google Analytics tracking code appear before the closing <\head> on html sites. The above method will do this.
If for some reason you want to include it in the body of the html code, you can simply include the GA code in the body of the rmd file by inserting it between the html_preserve command:
Google Analytics Code Here
source share