Connecting R with Google Analytics

R is a great open-source tool for visualizing data and there are plenty of libraries for connecting Google analytics too. In this tutorial, I will be using RStudio IDE with googleAuthR and googleAnalyticsR packages.

rstudiodata

Let’s start!

– Install R

– Install RStudio, the most commonly use IDE for R.

–  Now install googleAuthR and googleAnalyticsR packages

Latest in Rstudio, you will possibly find googleAuthR pre-installed at AddIns. googleAuthR is my preferred library as it continuously refreshes the Google analytics access token iwthout hassels.

– Now let’s start by configuring google analytics Aouth2

First, we need to create a  project  at Google Developer Console and generate OAuth2 token and clientSecret for WebAPP Type. Most important part here is adding authorized redirect URI that matches with your local callback listening PORT. We can leave Redirect URI if you don’t know for now and come back here later.

(Don’t forget to enable Google Analytics APIS)

rstat-auth2

 

Next, we will configure googleAuthR library with the credentials we created above. For this we will have 2 commands as bellow:

Once added we are now ready to connect and authenticate Google Analytics API, So click on Addins and select googleAuth.

rstudio-addins

 

rstudioauth2

 

Make sure that the ClientId you added in console appears here and Google Analytics is enabled at Google developer console. Now click on Login Button that will lead you through authentication. If Redirect URI in beginning of step 3 is wrong you will probably get an error like below, to solve this add the redirect URI the – API request details to the project console. (save and wait for some time, until it works.)

callback-error

When the project get updated, url will work and authentication process will request you to login or select your account and authorize permissions. On successful connection, you will get a message like below.

authentcated

 

 – Now, come back to Rstudio and start making a simple script to visualize data. For this use the script below:

 

Here “id” is Google Analytics profile ID (can be obtained from here ). Copy paste the code into script place and run the script. We will be making a line chart with Sessions Vs Date format.

 

rstudioresult

 

rstudioresult2

You can also use command lines to make modifications.

rstudioplotchart

 

That’s it, we are done with connecting GA with R and making visualizing first data set.