How to use gtag.js instead of analytics.js in a shiny app


#1

Hi. I must use gtag.js instead of analytics.js in my Shiny app, for Google Analytics tracking purpouses. I got to enable tracking (Step 1 in http://shiny.rstudio.com/articles/usage-metrics.html). But I don`t know how to enable event tracking (Step 2 in http://shiny.rstudio.com/articles/usage-metrics.html). Can I have some tips? Thanks.


#2

You don’t have to use gtag.js to get tracking its just the latest version of the script, so the older script will still work fine.

However if you want more customisation of the tracking script you can add the javascript directly to the ui.R either via includeScript() or otherwise - some examples from this template are below, which let you install GA, Google Tag Manager or your own:

trackingTags <- function(tag_template = c("ga","gtm","freeform"),
                         tag_code){


  tag_template <- match.arg(tag_template)


  out <- switch(tag_template,
                ga = sprintf("<script>
  (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','https://www.google-analytics.com/analytics.js','ga');

                             ga('create', '%s', 'auto');
                             ga('send', 'pageview');

                             </script>", tag_code),
                gtm = sprintf("<!-- Google Tag Manager -->
<noscript><iframe src=\"//www.googletagmanager.com/ns.html?id=%s\"
                height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe></noscript>
                <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
                new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
                j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
                '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
                })(window,document,'script','dataLayer','%s');</script>
                <!-- End Google Tag Manager -->", tag_code, tag_code),
                freeform = tag_code

                )

  HTML(out)
}

If you are looking to implement event tracking you have a couple of options -

  1. Use Google Tag Manager (that hosts the GA script) you can use its own custom click events to add things like button clicks into GA just using the GTM interface - this is by far the easiest way
  2. You can use the Measurement Protocol to make your own GA hits. This is the most customisable and a proto R library to help is this one - googleMeasureR, but you need to handle things like userIds yourself.