How can I always include the Google Analytics tacking code on my GitHub Pages webpage generated with R Markdown?
I am currently creating a webpage hosted on GitHub Pages using RMarkdown. To create site, I run rmarkdown::render_site()
. This command will knit all R Markdown documents to create the relevant .html
files.
However, I want to include Google Analytics on my site. To do this, I need to include a University Analytics tracking code to my property by pasting the JavaScript code in my main index.html
file. I can easily do this by editing the index.html
file directly. However, every time I run rmarkdown::render_site()
, to render the site, it re-knits the index.Rmd
file, and thus overwrites the index.html
file, including the Google Analytics code I previously entered directly.
How can I fix this problem and always have my Google Analytics code contained in the page?
Within a few hours Google Analytics should pick up the change, and you'll be capturing session times, demographics, and other useful information on visitors to your site.
I just figured out how to get this done while trying to add google analytics to my own RMD site on Github Pages.
</head>
tag of an html document produced from RMD...Step 1: Create a .html file containing the Google Analytics Script, and save it in the working directory for your site. (Simply, create new text file, paste script, save "filename.html".
Step 2: Adjust the yaml header of your rmd file to contain the includes: & in_header: arguments, and reference the .html file containing the tracking code
---
title: ""
output:
html_document:
includes:
in_header: GA_Script.html
---
Step 3: Adjust yaml headers for each rmd file related to your site so that each page reports back to Google Analytics.
It is recommended that the Google Analytics tracking code be placed before the closing <\head>
tag in the sites html. The method above will get that done.
If for some reason you want to include it in the body of the html code, you could just include the GA code in the body of the rmd file by pasting it in between an html_preserve command:
<!--html_preserve-->
Google Analytics Code Here
<!--/html_preserve-->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With