
Today I’m adding Google Analytics to an RShiny App I’m building named Shiny Impact. In doing so I noticed a new feature in Google analytics and that the instructions from RShiny here wouldn’t work and would need to be tweaked. Although a very mundane subject I figured I would use it to get used to Markdown.
Some Background
In case you missed it Google recently released a unified app and web analytics property. Implementation instructions can be found here. Typically when adding a new property the options were:
- Add a Website
- Add an App (using the mobile SDK)
- Add an App (via Firebase)
Earlier this year #2 was put on notice/deprecated. For reference:
For Universal Tracking Version
Anyhow the original instructions indicated that you would simply do the following:
- Create a new property
Obtain Google Tracking Code (note script tags were removed)
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date(); a=s.createElement(o), m=s.getElementsByTagName(o)[0]; a.async=1; a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-54514964-1', 'auto'); ga('send', 'pageview');
Save it to a file locally
Update Your R Code
tags$head(includeScript("google-analytics.js")),
This NORMALLY works fine however if you use the code from the new beta property this could break your app. This is because the function adds script tags. To avoid affecting any asynchronous business we can simply use an includeHTML tag shown below:
For New Apps and Web Property (Global Site Tag (gtag.js))
- Create a new property:
- Obtain the tracking code:
Save this code to google-analytics.html. Be sure to do so in the WWW folder for your shinyapp otherwise it may not find the file when it runs
<!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=XXXXX"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'XXXXX'); </script>
Update your Shiny App to include the code from within your UI function:
ui <- fluidPage( tags$head(includeHTML(("www/google-analytics.html"))), #other UI stuff )
Voila! Thereafter when you access your application it should start tracking visitor data etc. Below is a screen shot of the Realtime report verifying this.