Question

I found this code for Google Analytics which lets you analyze just a subset of data for your analytics.

_gaq.push(['_setSampleRate', '80']);

I want to do the same thing with Mixpanel but from what I understand SetSampleRate is a function that is specific to Google Analytics.

How might I do something like this in Mixpanel?

I have browsed their KB & Help articles but haven't found anything that talks about this.

Was it helpful?

Solution

All you have to do is create a Random number from 0 to 100 and check if it's lower than the sample target you have. If it's lower you track it, otherwise you don't.

The way _setSampleRate works in Google Analytics is that it samples by user not by hit. So when you generate the Random number you also have to store it in a cookie so that you can check for further interactions and either track it or not.

In the Example below I created a helper function that checks if the user is in the Sample and handles the cookie logic for me.

function inSample(target) { 
  var domain_name = 'mysite.com'; // CUSTOMIZE WITH YOUR DOMAIN
  var sampleCookie = 'mixpanel_sample='; // COOKIE NAME

  var current = document.cookie;

  if (current.indexOf(sampleCookie) > -1) {
    // Cookie already exists use it
    var current = document.cookie.substring(
      document.cookie.indexOf(sampleCookie) + sampleCookie.length
    );
    if (current.indexOf(';') > -1)
      current = current.substring(0,current.indexOf(';'));

    current = parseInt(current);
  } else {
    // Cookie not found calculate a random number
    current = Math.floor(Math.random()*100)

  }
    // reset the cookie to expire in 2 years
    var two_years = new Date();
    two_years.setTime(two_years.getTime() + 2*365*24*60*60*1000);
    two_years = two_years.toGMTString();

    document.cookie = sampleCookie + current + 
      '; domain=' + domain_name + '; path=/' + 
      ' ; expires=' + two_years + ';'

    return target >= current;
}

Now all you have to do is use this function in order to fire or not the mixPanel tracking Code.

if (inSample(80)) {
  // MIXPANEL TRACKING CODE GOES HERE
}

What you have in the end is a report in Mixpanel that only includes 80% of your users.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top