Category: Data Wrangling

 

Optimization Insights – Data Wrangling

Unleash the power of your data. Learn data wrangling tools & techniques to clean, shape, and analyze your raw data into actionable insights.

  • Using the Google Analytics Data API to Pull GA4 Data into Google Sheets

    The Google Analytics Data API is a powerful tool that enables you to access, process, and analyze your Google Analytics 4 data from anywhere, including Google Sheets. By using the API, you can pull data from Google Analytics 4 into a Google Sheets spreadsheet, where you can manipulate and visualize it in any way you need.

    Access Google Analytics 4 Data from Google Sheets

    The method outlined below is for advanced solutions that require more control or customization of the data transfer process, custom menu options, and user functionality in Google Sheets. For simple reports and data transfer needs, you can export data files from GA4 and import them into Google Sheets using the menu options in those tools. You can also use a Google Sheets Add-on such as the official GA4 Reports Builder for Google Analytics from Google, Michele Pisani’s GA4 Magic Reports Add-On, the SyncWith Google Sheets Add-on, or the API Connector for Google Sheets from Mixed Analytics, which all enable users to create and run reports on GA4 data from within Google Sheets.

    Any of those may serve as a quick and relatively easy method to perform most common tasks, but if you need more advanced functionality, read on…

    Basic Steps and Sample Code

    1. Enable the Google Analytics API. To do this, go to the Google Developers Console and select your project. Then, click the APIs & Services tab and search for Google Analytics Data API. Click the Enable button next to the API.
    2. Create a Google Sheets spreadsheet.
    3. Create a new Apps Script. In the spreadsheet, go to Extensions->Apps Script.
    4. Add the Google Analytics Data API client library to your script. In the Apps Script editor, click on the plus (+) sign next to the Services Headers to Add a Service. Scroll to find the Google Analytics Data API. Select the service and click the Add button.
    5. Write a script to pull data from Google Analytics 4. The following is a simple script that you can use to pull data from Google Analytics 4 into a Google Sheets spreadsheet. Feel free to start with this script and modify it as needed to suit your specific requirements.
    /* Copyright 2023 Optimization, LLC (o10n)
     * version 1 - Modified Dimensions & Metrics for this example and Added OrderBy functionality
     *
     * Derived from Google LLC, Copyright 2021
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     https://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    function pullDataFromGA4() {
      // Set the Google Analytics 4 property ID.
      const propertyId = 'YOUR_GA4_PROPERTY_ID';
      try {
        // Construct Dimensions Array
        const dimension = AnalyticsData.newDimension();
        dimension.name = 'date';
        // Construct Metrics Array
        const metricsArray = [];
        const totalUsers = AnalyticsData.newMetric();
        totalUsers.name = 'totalUsers';
        metricsArray.push(totalUsers);
        // Construct Date Range
        const dateRange = AnalyticsData.newDateRange();
        dateRange.startDate = '7daysAgo';
        dateRange.endDate = 'yesterday';
        // Construct Order By
        const orderBy = AnalyticsData.newOrderBy();
        orderBy.desc = false;
        const dimOrderBy = AnalyticsData.newDimensionOrderBy();
        dimOrderBy.dimensionName = dimension.name;
        dimOrderBy.orderType = 'NUMERIC';
        orderBy.dimension = dimOrderBy;
         
        // Construct Report Request
        const request = AnalyticsData.newRunReportRequest();
        request.dimensions = [dimension];
        request.metrics = [metricsArray];
        request.dateRanges = dateRange;
        request.orderBys = orderBy;
        // Run the report.
        const response = AnalyticsData.Properties.runReport(request, 'properties/' + propertyId);
        // Get Active Sheet and Clear All Data
        const sheet = SpreadsheetApp.getActiveSheet();
        sheet.clear();
       
        // Construct Header
        const dimensionHeaders = response.dimensionHeaders.map(
            (dimensionHeader) => {
              return dimensionHeader.name;
            });
        const metricHeaders = response.metricHeaders.map(
            (metricHeader) => {
              return metricHeader.name;
            });
        const headers = [...dimensionHeaders, ...metricHeaders];
        // Write Header to Sheet
        sheet.appendRow(headers);
       
          // Construct Row Data
          const rows = response.rows.map((row) => {
            const dimensionValues = row.dimensionValues.map(
                (dimensionValue) => {
                  return dimensionValue.value;
                });
            const metricValues = row.metricValues.map(
                (metricValues) => {
                  return metricValues.value;
                });
            return [...dimensionValues, ...metricValues];
          });
          // Write Row Data to Sheet
          sheet.getRange(sheet.getLastRow(), 1, response.rows.length, headers.length)
              .setValues(rows);
      } catch (e) {
        console.log('Failed with error: %s', e.error);
      }
    }

    To use the script, replace YOUR_GA4_PROPERTY_ID with the ID of your Google Analytics 4 property. You can find the property ID in the Google Analytics 4 interface (it’s the ID listed in Admin->Property Settings).

    Once you have replaced the property ID, you can run the script by clicking the Run button in the script editor. The script will pull data from Google Analytics 4 and write it to the spreadsheet.

    You can modify the script to pull different dimensions and metrics, or to filter the data. You can also use the script to pull data from multiple Google Analytics 4 properties or to pull data from different date ranges. Visit the Google Apps Script Analytics Data Service API Reference, for more information.

    Examples of using Apps Script with the Google Analytics Data API

    There are many benefits to using the Google Analytics Data API to pull data from GA4 into a Google Sheets spreadsheet:

    • Automated Data Retrieval: Automate the data pull process, so that you don’t have to manually export data from Google Analytics 4 into Google Sheets.
    • Data Aggregation: Easily combine data from multiple sources like Google Analytics 4, CRM, or ERP into one spreadsheet.
    • Data Flexibility: Re-Organize, manipulate and filter data in any way you need to.
    • Tailored Reporting: Create custom reports and visualizations that are tailored to your specific needs.
      BONUS ECommerce SEO Tip – Identify products with the most organic search traffic and no sales (zero-converting organic search traffic) by importing visitor source, landing page, and order data. Filter to product pages from organic search, with no sales orders, and sort by page views in descending order. Analyze these pages to determine why they aren’t converting!
    • Custom Menus and Functions: With Google Apps Script, you can create custom functions and menus in Google Sheets (and other Google Workspace apps) that extend your data processing capabilities and provide users with more control.

    Google Sheets and the Google Analytics Data API are both powerful tools for marketers, analysts, and website owners. Combining them will help you unlock the full potential of your GA4 data.


    Can We Assist?
    Expert Advice in Just a Few Clicks
    Name
    How Can We Help?
  • Using Apps Script to Transfer Data Between Google Sheets

    This article shows how to create a simple Google Apps Script to import data from one Google Sheet to another Google Sheet. This capability can be used automate data transfers, keep data in sync, and simplify data aggregation for reporting and analysis, making it easier to keep your data up-to-date and centralized.

    Transfer Data Between Google Sheets

    Create a Simple Apps Script in Google Sheets

    1. Prepare Your Google Sheets
      Before diving into Google Apps Script, ensure that you have two Google Sheets ready:
      • Source Sheet: This is the external Google Sheet that contains the data you want to import. Make sure it’s accessible to your Google account and has the data organized with clear headers.
      • Destination Sheet: This is the Google Sheet where you want to import the data. It should have a structure that matches the data you’re importing or be ready to accommodate the incoming information.
    2. Access Google Apps Script
      • To begin, open your destination Google Sheet and navigate to the “Extensions” menu, then select “Apps Script.” This opens the Google Apps Script editor, where you’ll write your custom script.
    3. Script Development
      • In the Apps Script editor, write a custom script that specifies how to retrieve data from the source Google Sheet and insert it into the destination sheet (sample script below). The script involves identifying the source sheet, selecting the data to be imported, and pasting it into the destination sheet. You can also include error handling and data formatting as needed.
      • You can use methods from the Google Class Spreadsheet to construct code that processes the data however you need.
    4. Testing and Execution
      • Once you’ve developed the script, save it, and run it directly from the Apps Script editor. Be prepared to authorize the script to access your Google Sheets. Your script is associated with the Google Sheet you’re working in and can always be accessed from the Extensions menu or at https://script.google.com.

    Sample Apps Script to Import Data from Another Google Sheet

    function importData() {
      // Replace with the ID of the source spreadsheet
      const sourceSpreadsheetId = "###############";
      // Replace with the name of the source sheet
      const sourceSheetName = "Sheet1";
      // Replace with the range of data to import (e.g., "A1:B10")
      const sourceRange = "A1:D";
      // Access the source spreadsheet
      const ss = SpreadsheetApp.openById(sourceSpreadsheetId);
      const sourceSheet = ss.getSheetByName(sourceSheetName);
      // Get the data from the source range
      const sourceValues = sourceSheet.getRange(sourceRange).getValues();
      // Access the destination spreadsheet (the current one)
      const destSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
      // Replace with the name of the destination sheet
      const destSheetName = "Sheet2";
      const destSheet = destSpreadsheet.getSheetByName(destSheetName);
      // Clear the existing data in the destination range (optional)
      destSheet.getRange(sourceRange).clearContent();
      // Set the imported data to the destination range
      destSheet.getRange(sourceRange).setValues(sourceValues);
    }

    Summary

    Google Apps Script opens up a world of possibilities for automating data between Google Sheets. By following the steps outlined above, you can streamline your data management and reporting tasks, ensuring that your information is always up-to-date and readily accessible. Dive in today and begin harnessing the potential of this versatile tool to simplify your workflow and transform your data-management workload.

  • Google Apps Script

    Google Apps Script is a versatile tool for optimizing tasks and tailoring experiences. Developed by Google, this scripting language allows users to automate actions and expand the functionality of Google applications. Whether you’re a coding expert or a novice, grasping the fundamentals of Google Apps Script can unlock efficiency and innovation.

    Google Workspace

    But What Is It?

    Google Apps Script is a cloud-based JavaScript platform enabling users to create personalized applications, automate routines, and seamlessly integrate with diverse Google services. Its primary purpose is enhancing Google Workspace applications like Sheets, Docs, Gmail, and Drive. Individuals can customize these applications by crafting code within Apps Script to align with specific needs.

    What Can It Do?

    Apps Script isn’t just a tech concept; it’s a practical solution that can transform the way you use Google applications. Here are some real-world examples of what Apps Script can do:

    • Add custom menus, dialogs, and sidebars to perform functions in Google Sheets, Docs, Forms…
    • Automate and Schedule Tasks in Google Sheets, Docs, Forms…
    • Connecting with other Google Services like Google Analytics, Drive, Gmail, YouTube, etc.
    • Pull Data from corporate/enterprise CRM and ERP systems.
    • Create Web Apps, & much more!

    These examples barely scratch the surface of what Apps Script can achieve. From simplifying your workflow to creating entirely new tools, this scripting platform puts you in control of your digital experience. So, whether you’re streamlining tasks or dreaming up new ways to work smarter, Google Apps Script has the potential to be a valuable resource in your technological toolkit.

  • Exporting Universal Analytics Data with GA Query Explorer

    Google officially announced that on July 1, 2024, access to the Universal Analytics (GA3) user interface and API will be discontinued for all users, including those utilizing Google 360 properties. To address this, here’s a free and simple solution to archive your data, or easily export it to merge with data from GA4 or other sources.

    How to Use Google Analytics Query Explorer for UA Data Export

    This tool can be used for GA4 data as well, but this list focuses specifically on the UA Query Explorer. Here’s a step-by-step breakdown of how to use this powerful resource:

    1. Open Google Analytics Query Explorer at ga-dev-tools.google/query-explorer/
    2. Select Your Account and Property: Begin by signing into your Google account and select the specific account, property, and view that you want to work with. This sets the foundation for your setting up your data export queries.
    3. Set Query Parameters: The “Set query parameters” section is where most selections happen
      • Date range: This is where you select the date range for your query. You can use any of the following formats to select the dates
        • Calendar date, such as 2021-01-31
        • Relative date, such as today or yesterday
        • NdaysAgo value, such as 30daysAgo or 7daysAgo
      • Metrics: These are quantitative measurements that provide insights into different aspects of user interaction. You could run the query here to make sure that all of the metrics that you chose are compatible. (Examples- Pageviews, New Users, or Impressions)
      • Dimensions: These are the qualitative attributes that provide some context to your metrics. they answer questions like “How did users arrive at my site?” and “Where are my users located?”. (Examples: Source/Medium, Country or Region, and Device Category)
      • Filters (optional): Allow you to narrow down your data set to focus on specific subsets of information.
      • Segments (optional): Enable you to isolate specific groups of users or sessions within your data for more targeted analysis.
    4. Run Query: With your parameters in place, hit the “Run Query” button. The Query Explorer will generate a report of your specific data and list it at the bottom of the page
    5. Export: Once you have your report, you can export it as a TSV file. This way your data is stored outside of Google Analytics and the Query Explorer, and free for you to use in any way you need. Alternatively, you can copy the API Request URL to integrate the data into other applications.
    6. Repeat: Repeat the process above to archive all the metrics and dimensions that you may want to archive for future reference.

    In a world where data reigns supreme, having the ability to archive your Universal Analytics data before it fades away is an opportunity you shouldn’t miss. There are many other ways to do this, 1) Exporting Individual Reports directly from UA, 2) Using the Google Analytics Reporting API, 3) Using one of the Google Sheets Add-Ons, 4) using Big Query (great for large data sets). Here’s a link for more info – https://support.google.com/analytics/answer/11583528#export.

    While there are numerous paths available, the Google Analytics Query Explorer and related UA Dimensions & Metrics Explorer (available on the same site) will empower you to explore the UA data available and make it relatively easy to query and export the data to files you want to archive.


    Can We Assist?
    Expert Advice in Just a Few Clicks
    Name
    How Can We Help?