Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Google Analytics in an RMarkdown generated GitHub Page?

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?

like image 790
Nathaniel Phillips Avatar asked Dec 29 '16 09:12

Nathaniel Phillips


People also ask

Can I add Google Analytics to Github pages?

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.


1 Answers

I just figured out how to get this done while trying to add google analytics to my own RMD site on Github Pages.

To add Google Analytics code before the closing </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-->
like image 185
balexturner Avatar answered Sep 27 '22 23:09

balexturner