I recently wanted to add a Google Analytics tracker to a Shiny dashboard, and I found that the official documentation doesn’t explain how to include “Global Site Tag” tracking code, which seems to be the current default setting in Analytics. The process is simple, we just have to include the tracking code as an HTML snippet in
ui.R. The process requires only two steps:
- Copy the analytics HTML snippet into a text file
- Reference the file in
1. Find and copy the tracker snippet
You’ll find this snippet on your Analytics console, in Admin > Tracking Info > Tracking Code. You may need to create a Property first, from the drop-down menu of the Property column in the Admin console.
I created a file named
google-analytics.html, in the same directory as
ui.R, and copied into it the HTML snippet, which looks like this:
The x’s should of course be replaced by your own id.
2. Reference the file in ui.R
Next, include the file in
ui.R, towards the top of your fluidPage:
shinyUI(fluidPage( tags$head(includeHTML(("google-analytics.html"))), ...
That’s all! Your published app will now send visitor statistics to Google Analytics.
The official Shiny docs are still relevant for more information on creating Properties (https://shiny.rstudio.com/articles/google-analytics.html) and more advanced usage, such as tracking individual events on the page (https://shiny.rstudio.com/articles/usage-metrics.html).