How to add Google Analytics to a Shiny application

February 21, 2018
By

(This article was first published on R on Programming notes, and kindly contributed to R-bloggers)

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:

  1. Copy the analytics HTML snippet into a text file
  2. Reference the file in ui.R

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.

Further reading

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).

To leave a comment for the author, please follow the link and comment on their blog: R on Programming notes.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)