Hello There!

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Web Page Sequencing Analysis Using Google Analytics

Recently on a project, we were trying to implement the network path diagram and carry out an analysis with the website’s page sequence data to know if there exists a specific traversing pattern among visitors.

While there is a lot of visual representation available (such as Paditrack) of a sequence of pages visitor follows the real beauty is having a such sequence as row data to have them analyzed.

For example, if you know a specific visitor pattern is always observed before a visitor initiates the sale, it would be great to know that. If you know a specific content consumption results in visitors returning to the website the next day, it would be awesome for you.

By having data for sequences in raw format, you are aided with a tool that you can collect those data and eventually carry out such beautiful analysis.

We are using an anonymous visitor id for each visitor in one custom variable on the visitor level and set another custom variable on the page level to have the incremented counter value which is stored and accessed from the cookies.

Implementation:

  1. Download the script “Page Counter Script” from the JavaScript Resource section (PageCounter Script).
  2. Unzip the content and include the script on all the pages of your website.
  3. When you are done with the implementation on all pages of your website check with the implementation using “Omnibug” in Firefox or using the Developer tool in Google Chrome.
  4. Once you see the gif requests are made to the GA server and data would show under All Pages in Google Analytics.
  5. Don’t forget to create a different view to separate the page counter virtual Pageviews from the main view so that it does not affect the bounce rate.

Note: We have used one custom variable and virtual pageview as follows:

Custom Variable 5 Visitor Level Constant through the visitor-level cookie existence. Stores randomly generated anonymous visitor id
Virtual Pageview Page Level Page sequence counter stores page URL with sequence counter incremented by 1 on each visit of a page as a virtual pageview

How does it work?

  1. We initialize a visitor id in one custom variable which sets to visitor level upon first visit using the Visitor Id script and set a page counter cookie value to 1 and send it to GA using virtual pageview. You can download the Visitor Id script from the JavaScript Resource section (Visitor ID tracking). In our case “vid” is customVar5.
  2. Once the visitor browses through other pages in session; the page counter value is incremented by one and the value is submitted to GA using trackpageview or trackEvent call.
  3. On the next visit, the page counter cookie value resets to 1 and begins the new counter for the new session
  4. This page counter value and the page URL are sent to GA using trackpageview (Virtual pageview). Note: You can also use Events to send page counter data to GA using trackEvent.
  5. All the data can be extracted using GA API as mentioned below. Which can be used to represent the visual flow from a page to another page.

Google Analytics would show reports as follows:

Visitor Id Data:

Page Counter Data:


Note: it would show the above data only when using trackpageview. You can use event data for the calls made through trackevents.

Data extraction of the data collected:

Once the tracking is implemented on all pages and data is collected on the GA interface. You can use data query feed explorer from Google Analytics using GA API v3 or use our Excel plugin Data should be similar to the image below.

Reference:

  1. Visitor Id: Unique visitor id.
  2. Virtual pageview: Pageviews with the page URL and page sequence data.
  3. Visit Count: Visit count of a visitor.
Dimensions, Metrics, and Filters
Dimensions: ga:customVarValue5, ga:pagePath, ga:visitCount Note: Change the custom Variable number if you have changed while implementation
Metrics: ga:pageviews (Virtual pageview call to send page counter info to GA in the script)
or
ga:totalEvents (Event call to send page counter info to GA in the script)
Filter: ga:customVarName5== vid;ga:pagePath=@ /vp/pgc Note: if you have changed the custom variable names then please update here too.

 

How it is different from Page-Depth
Page Depth gives you a count of pages viewed by visitors in a session. Whereas Page Sequence gives you which pages a visitor visited in a session along with its sequence.

Benefits:

  • You can know how user follows through pages and can know the navigation trail easily.
  • You can find what are the pages which are important and makes users interact with your website
  • Helps you identify pages from where a user leaves your website if conversions are not happening. So that you can implement strategies to win your customers.

Want to implement this solution on your website and do the data analysis? Contact us

Google analytics data extraction in R

oauth2

Unlike other posts on this blog, this particular post is more focused on coding using R so an audience with a developer mindset would like it more than pure business analysts.

My goal is to describe an alternative method to use to extract the data from Google Analytics via API into R. I have been using R for quite some time but I think the GA library for R has been broken and while they did make an update, it’s sort of not being used right now.

Considering this, I thought to write it down by myself on moving on as more data-related operations are now being done using R.

Moreover, the Rgoogleanalytics package that is available is built for Linux only and my Windows friends may just like me to have something for them as well.

Ok so let’s get started, it’s going to be very quick and easy.

There are some prerequisites for GA Data extraction in R:

  1. At least one domain must be registered with your Google analytics account
  2. R installed with the following the Googleng packages

Steps to be followed for Google Analytics data extraction in R :

Set the Google Analytics query parameters for preparing the request URI:

To extract the Google Analytics data, first, you need to define the query parameters like dimensions, metrics, start date, end date, sort, and filters as per your requirement.

# Defining Google analytics search query parameters

# Set the dimensions and metrics
ga_dimensions <- 'ga:visitorType,ga:operatingSystem,ga:country'
ga_matrics <- 'ga:visits,ga:bounces,ga:avgTimeOnSite'

# Set the starting and ending date
startdate <- '2012-01-01'
enddate <- '2012-11-30'

# Set the segment, sort and filters
segment <- 'dynamic::ga:operatingSystem==Android'
sort <- 'ga:visits'
filters <- 'ga:visits>2'
Get the access token from Oauth 2.0 Playground

We will obtain the access token from Oauth 2.0 Playground. Following are the steps for generating the access token.

  1. Go to Oauth 2.0 Playground
  2. Select Analytics API and click on the Authorize APIs button with providing your related account credentials
  3. Generate the access token by clicking on the Exchange authorization code for tokens and set it to the access token variable in the provided R script
Retrieve and select the Profile

From the below, you can retrieve the number of profiles registered under your Google Analytics account. With this, you can have the related GA profile id. Before retrieving profiles ensure that the access token is present.

We can retrieve the profile by requesting to Management API with accesstoken as a parameter, it will return the JSON response. Here are the steps to convert the response to the list and store it in to the data frame object profiles.

# For requesting the GA profiles and store the JSON response in to GA.profiles.Json variable
GA.profiles.Json <- getURL(paste("https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties/~all/profiles?access_token=",access_token, sep="", collapse = ","))

# To convert resonse variable GA.profiles.Json to list
GA.profiles.List <- fromJSON(GA.profiles.Json, method='C')

# Storing the profile id and name to profile.id and profile.name variable
GA.profiles.param <- t(sapply(GA.profiles.List$items,
                              '[', 1:max(sapply(GA.profiles.List$items, length)))) 
profiles.id <- as.character(GA.profiles.param[, 1])
profiles.name <- as.character(GA.profiles.param[, 7])

# Storing the profile.id and profile.name to profiles data.frame
profiles <- data.frame(id=profiles.id,name=profiles.name)

We have stored the profiles information in profiles data frame with profile id and profile name. We can print the retrieved list by following code

profiles
OUTPUT::

         id       name
1 ga:123456    abc.com
2 ga:234567    xyz.com

At a time we can retrieve the Google analytics data from only one GA profile. so we need to define the profile id for which we want to retrieve the GA data. You can select the related profile id from the above output and store it in to profileid variable to be later used in the code.

# Set your google analytics profile id
profileid <- 'ga:123456'
Retrieving GA data

Requesting the Google Analytics data to Google analytics data feed API with an access token and all of the query parameters defined as dimensions, metrics, start date, end date, sort, and filters.

# Request URI for querying the Google analytics Data
GA.Data <- getURL(paste('https://www.googleapis.com/analytics/v3/data/ga?',
                        'ids=',profileid,
			'&dimensions=',ga_dimensions,
                        '&metrics=',ga_matrics,
			'&start-date=',startdate,
                        '&end-date=',enddate,
                        '&segment=',segment,
			'&sort=',sort,
			'&filters=',filters,
                        '&max-results=',10000,
                        '&start-index=',start_index*10000+1,
                        '&access_token=',accesstoken, sep='', collapse=''))

This request returns a response body with the JSON structure. Therefore to interpret these response values we need to convert it to a list object.

# For converting the Json data to list object GA.list
GA.list <- fromJSON(GA.Data, method='C')

Now its easy to get the response parameters from this list object. So, the total number of the data rows will be obtained by the following command

# For getting the total number of the data rows
totalrow <-  GA.list$totalResults
Storing GA data in a Data frame

Storing the Google Analytics response data in R dataframe object which is more appropriate for data visualization and data modeling in R

# Splitting the ga_matrics to vectors
metrics_vec <- unlist(strsplit(ga_matrics,split=','))

# Splitting the ga_dimensions to vectors
dimension_vec <-unlist(strsplit(ga_dimensions,split=','))

# To splitting the columns name from string object(dimension_vec)
ColnamesDimension <- gsub('ga:','',dimension_vec)

# To splitting the columns name from string object(metrics_vec)
ColnamesMetric <- gsub('ga:','',metrics_vec)

# Combining dimension and metric column names to col_names
col_names <- c(ColnamesDimension,ColnamesMetric)
colnames(finalres) <- col_names

# To convert the object GArows to dataframe type
GA.DF <- as.data.frame(finalres)

Finally the retrieved data is stored in GA.DF dataframe. You can chek it’s top data by the following command

head(GA.DF)
OUTPUT::
        visitorType operatingSystem   country visits bounces      avgTimeOnSite
1       New Visitor         Android Australia      3       1              106.0
2       New Visitor         Android   Belgium      3       1 155.33333333333334
3       New Visitor         Android    Poland      3       0               60.0
4       New Visitor         Android    Serbia      3       2 40.666666666666664
5       New Visitor         Android     Spain      3       1               43.0
6 Returning Visitor         Android (not set)      3       3                0.0

You will need this full R script for trying this yourself, You can download this script by clicking here. Currently, I am working on the development of R package, which will help R users to do the same task with less effort. If anyone among you is interested provide your email id in the comment, and we’ll get in touch.

Would you like to understand the value of predictive analysis when applied to web analytics data to help improve your understanding relationship between different variables? We think you may like to watch our Webinar - How to perform predictive analysis on your web analytics tool data. Watch the Replay now!

 

Bot Icon
Bot Icon

Tatvic Bot

Explore About Tatvic and Services