Connecting R with Google Analytics

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.


Let’s start!

– Install R

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

–  Now install googleAuthR and googleAnalyticsR packages


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

– Now let’s start by configuring google analytics Oauth2

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 this for now and come back to this later.

(Don’t forget to enable Google Analytics API at developer console)



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

options("googleAuthR.webapp.client_id" = "")
options("googleAuthR.client_id" = "")
options("googleAuthR.client_secret" = "tokenparts-eHriGfPWtidRWNtII1pLUhF")

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





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.)


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.



 – Now, come back to Rstudio and make a simple script to visualize data. Try using the example below:

gadata <- google_analytics(id = "ga:632597", 
                           start="2016-08-01", end="2016-12-02", 
                           metrics = c("sessions"), 
                           dimensions = c("date"))
plot(gadata, type="l", col="red")


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.





You can also use command lines to make modifications.



That’s it! we are done with connecting Google Analytics with R and visualizing a data set.


Read more