Monitoring Event with R Shiny Inputs and Google Analytics

Can anyone provide guidance on how to track events using Google Analytics and R Shiny?

I want to monitor the user's interaction with my apps, specifically keeping track of which inputs they select. For instance, I am interested in knowing when a user interacts with the 'PointUseInput' checkbox input.

I attempted to follow the instructions provided here, but since I am not very familiar with JavaScript, I am unsure about how to structure the ga function properly.

# ################################################################################################
# ################################################################################################
# # Sec 1a. Needed Libaries & Input Files

library(shiny)
library(shinydashboard)
library(leaflet)
library(dplyr)

##The Data
Map_DF <- data.frame("Point_ID" = c("A1", "B1", "C3"), 
                     "Latitude" = c(38.05, 39.08, 40.05), 
                     "Longitude" = c(-107.00, -107.05, -108.00),
                     "PointUse" = c("farm", "house", "well"))


################################################################################################
################################################################################################
#UI
ui <- dashboardPage(
    
    dashboardHeader(), 
    
    dashboardSidebar(
        

       ### tags$head(includeHTML(("google-analytics.html"))),  #Google Analytics html tag here
        
        
        checkboxGroupInput(inputId = "PointUseInput", label = "Select Point Use", choices = Map_DF$PointUse, selected = Map_DF$PointUse)
    ), 
    
    dashboardBody(
        fluidRow(leafletOutput(outputId = 'mapA'))
    )
)

################################################################################################
################################################################################################
server <- function(input, output, session) {
    
    ## The Filter
    filterdf <- reactive({
        Map_DF %>% 
            filter(PointUse %in% input$PointUseInput)
    })
    
    ## Base Map Creation
    output$mapA <- renderLeaflet({
        
        leaflet() %>%
            addProviderTiles(
                providers$Esri.DeLorme,
                options = providerTileOptions(
                    updateWhenZooming = FALSE,
                    updateWhenIdle = TRUE)
            ) %>%
            setView(lng = -107.50, lat = 39.00, zoom = 7)
    })
    
    ## Update Map with Filter Selection
    observe({
        leafletProxy("mapA", session) %>% 
            clearMarkers() %>% 
            addCircleMarkers(
                data = filterdf(),
                radius = 10,
                color = "red",
                lat = ~Latitude,
                lng = ~Longitude,
                popupOptions(autoPan = FALSE),
                popup = ~paste("PointUse: ", filterdf()$PointUse))
    })
    
}

################################################################################################
################################################################################################
shinyApp(ui = ui, server = server)

Incorporating the corresponding google-analytics JavaScript Code...

  $(document).on('change', 'select', function(e) {
    ga('send', 'event', 'category', 'action', 'label', value);
  });

Answer №1

After experimenting with the google-analytics JavaScript Code, I discovered that this syntax worked best for me:

gtag('event', <action>, {
  'event_category': <category>,
  'event_label': <label>,
  'value': <value>
});

Rather than using:

 $(document).on('change', 'select', function(e) {
    ga('send', 'event', 'category', 'action', 'label', value);
  });

I recommend trying:

 $(document).on('change', 'select', function(e) {
    gtag('event', 'action', {
     'event_category': 'category',
     'event_label': 'label',
     'value': <value>
    });
  });

Another option to consider is:

 $('#selectInputId').on('change', function(e) {
    gtag('event', 'action', {
     'event_category': 'category',
     'event_label': 'label',
     'value': <value>
    });
  });

This was the simple change I implemented after reading through the article you shared.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Unable to reach essential Node.js modules

After attempting to deploy Next.js on Cloudflare Pages, I encountered the following error: Error: Could not access built-in Node.js modules. It is recommended to ensure that your Cloudflare Pages project has the 'nodejs_compat' compatibility flag ...

Create a function called plagiarismChecker that requires two parameters: an array containing the students' responses, and a small snippet of text

Write a custom function called detectPlagiarism that accepts two parameters: an array of student responses and a snippet of text to check for plagiarism. The function should return true if any of the essay question answers contain the specified text, and f ...

I attempted to utilize Ajax to invoke my PHP function, but I'm having trouble pinpointing the issue as the code doesn't seem to be functioning correctly

!-- Welcome to the Main Page -- <section class="container"> <div class="row"> <div class="centerlogin"> <div class="frmlogin"> <form role="form" name="signin" id="signin" method="post" action="#"> ...

Is it possible to open a new tab window using a radio button?

Looking for assistance with radio buttons. I want users to be redirected to a new window when they click the submit button beneath the radio buttons. If anyone has a solution, please help! I have tried using window.location.href and window.open but the c ...

Modifying specific attributes of an object within the $scope: A step-by-step guide

When working with Angular, if you have code in the view that looks like this: <span ng-model="foo.bar1"></span> <span ng-model="foo.bar2"></span> <span ng-model="foo.bar3"></span> Due to how Angular maps objects, you c ...

Using HTTPS, you can access Flask from AJAX

I have encountered numerous inquiries concerning this issue, but none have proven effective for me. I recently switched my domain from HTTP to HTTPS. Everything was functioning properly on HTTP. The main issue lies in the fact that my javascript and flask ...

Utilizing Python for extracting text from dynamically generated web pages with JavaScript

Is there a way to write a script in Linux that can extract text from a page generated by Javascript, specifically using etherpad (for example, http://www.board.net)? I have not been able to find an existing tool that fits my needs, such as lynx which doesn ...

The usage of Cross-domain AJAX GET parameters is restricted

Currently, I am attempting to retrieve data from an API using JavaScript, but unfortunately I am encountering an error in the process. $.ajax({ dataType: "jsonp", url: "https://www.bitstamp.net/api/ticker/", type: "GET", succes: myfunction ...

Steps to displaying the result

new Vue({ data: { folders : [{ name : 'folder1', isActive : 1, }, { name : 'folder2', isActive : 0, }, ] } } }) Is there a way to access the active val ...

trouble with v-for in Vue.js causing data not to show on page

Whenever I use console.log(e.data), I am able to retrieve values, but when attempting to display them using v-for, the data does not show up. Can someone please explain why this issue is occurring? Below is the HTML code intended to display the values: & ...

Transferring values from jQuery AJAX to Node.js

Is there a way to successfully pass a variable from jQuery to nodejs without getting the [object Object] response? I want to ensure that nodejs can return a string variable instead. $('.test').click(function(){ var tsId = "Hello World"; ...

Utilizing Bootstrap 5 for Angular Projects

With the release of version 5, the Bootstrap framework has eliminated the need for jQuery. I am curious about how this change impacts Angular applications. Can we still utilize all of Bootstrap's features in Angular, such as dropdowns? In the past, ...

A step-by-step guide to implementing cron jobs in Blitz.js

Seeking guidance on cron job implementation with Blitz.js I am in need of assistance with setting up a cron job using Blitz.js. I have already carefully reviewed the Blitz.js documentation. Progress so far I have thoroughly checked the Blitz.js document. ...

Dynamic Filtering of HTML Dropdown Options Based on Another Dropdown Selection

I am facing an issue with multiple HTML dropdowns. My requirement is that upon selecting an option from one dropdown, the next dropdown should get automatically populated. The data to populate these dropdowns is fetched from a database using SQL statements ...

Navigate to a specific hidden div that is initially invisible

Currently, I am working on a web chat application using next.js. The app includes an emoji picker button, which, when clicked, displays a menu of emojis. However, the issue I am facing is that the user has to scroll down in order to see the emoji menu. I a ...

Executing an animation in Angular 4 using a Directive

There's an ongoing issue on the repository here, but I wanted to see if anyone here could help as well. I am trying to programmatically trigger an animation from a Directive. However, when using Renderer.animate, I receive the following error: Rende ...

Extract data from an RSS feed and showcase it on an HTML webpage

Having trouble parsing a Yahoo Finance RSS news feed and displaying the information on a webpage. I've tried different methods but can't seem to get it right. Hoping someone out there can assist me with this. I came across a tutorial on how to p ...

React's setState function fails to propagate state changes to child components

Here is the structure of my component: ExchangeRateInput ExhangeRateValueInput ExhangeRateDialog The state open is passed through to ExhangeRateDialog as a prop. However, when I set the state open to true in ExchangeRateInput, it doesn't seem ...

Using acast (from the reshape2 package) in a function in R: Tips and tricks

In attempting to utilize the acast function from the package reshape2 within a custom function, I encountered an issue where acast was unable to locate the data being passed to it. Below is the sample data used: library("reshape2") x <- data.frame(1:3 ...

Is there a way to intercept all AJAX requests in JavaScript?

Could there be a universal event handler for ajax requests that is automatically triggered upon the completion of any ajax request? This is something I am exploring while developing a greasemonkey script for an ajax-heavy website. In past scripts, I have ...