Google Analytics for Shiny Dashboard App

Pau*_*aul 2 javascript google-analytics r shiny shiny-server

我有一个运行良好的R闪亮(shinydashboard)应用程序,可以在服务器上运行。我希望能够跟踪其使用情况,并知道Google Analytics(分析)是一个很好的解决方案。但是我遇到了设置它的问题。

我已经尝试按照此处描述的指示进行操作https://shiny.rstudio.com/articles/google-analytics.html

他们建议创建一个google-analytics.js脚本,其中包含google的全局站点标签:

<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-4XXXXX5-2">
</script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'UA-4XXXXX5-2');
</script>
Run Code Online (Sandbox Code Playgroud)

然后,他们建议在闪亮的应用程序标题中调用此“ google-analytics.js”脚本文件,如下所示:

#ui.r
library(shiny)
shinyUI(fluidPage(

  tags$head(includeScript("google-analytics.js")),
  includeCSS("cerulean.css"),

  titlePanel("Sunlight in the US"),
Run Code Online (Sandbox Code Playgroud)

但是,因为我使用的是闪亮的仪表板,所以我的闪亮布局有所不同...

#ui.r
library(shiny)
library(shinydashboard)

dashboardPage(

  dashboardHeader(title = "Single Cell Database"),

  dashboardSidebar(
    sidebarMenu(
      menuItem("P15 Clustering", tabName = "P15_Cluster", icon = icon("th")),
      menuItem("P15 Violin Plots", tabName = "P15_Violin", icon = icon("th"))
    )),

  dashboardBody(
    tabItems(
      tabItem(tabName = "P15_Cluster",
Run Code Online (Sandbox Code Playgroud)

我似乎无法弄清楚放置...的位置

tags$head(includeScript("google-analytics.js")),
Run Code Online (Sandbox Code Playgroud)

...以闪亮的仪表板格式显示。此外,由于googles代码格式不再与示例匹配,因此我不确定脚本函数的新格式。

对于在闪亮的仪表板标题内何处调用“ google-analytics.js”脚本或如何在“ google-analytics.js”文件内设置代码格式的任何帮助或建议,将不胜感激!

小智 5

我也有同样的问题 我可以解决问题,并且可以按照https://shiny.rstudio.com/articles/usage-metrics.html上的教程进行操作

第一步:您可以在google-analytics.js文件中使用以下代码:

(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', 'UA-4XXXXX5-2', 'auto');
ga('send', 'pageview');

$(document).on('change', 'select', function(e) {
    ga('send', 'event', 'widget', 'select data', $(e.currentTarget).val());
});

$(document).on('click', 'button', function() {
  ga('send', 'event', 'button', 'plot data');
});
Run Code Online (Sandbox Code Playgroud)

第二,您可以在“ dashboardBody”中调用文件“ google-analytics.js”。例如以下语法:

dashboardBody(
    tags$head(includeScript("google-analytics.js")),
    tabItems(
      tabItem(tabName = "P15_Cluster",
Run Code Online (Sandbox Code Playgroud)