The GAR - Google Analytics for R package - is designed to help easily retrieve data from Google Analytics. The following tutorial walks through set up, authentication and requesting data.
Note: For obvious reasons, permission/access to at least one Google Analytics Account is necessary.
install.packages('GAR', type=source) library(GAR)
GAR_CLIENT_ID <- 'client id copied from API Console' GAR_CLIENT_SECRET <- 'client secret copied from API Console'
getCode(GAR_CLIENT_ID)
GAR_REFRESH_TOKEN <- getRefresh(GAR_CLIENT_ID, GAR_CLIENT_SECRET, code)
Note: Initial authentication and retreiving the refresh token is a one time requirement. Repeating these steps is only necessary if authentication is revoked or if the Client ID, Client Secret or Refresh token is misplaced.
tokenRefresh(GAR_CLIENT_ID, GAR_CLIENT_SECRET, GAR_REFRESH_TOKEN)
df <- gaRequest( id=c('ga:123456789','ga:987654321'), dimensions='ga:date,ga:month', metrics='ga:sessions, ga:users, ga:pageviews', start='YYYY-MM-DD', end='YYYY-MM-DD', sort='-ga:sessions,ga:users' )
In addition to the requested dimensions and metrics, the data frame output of gaRequest() contains information about the request:
This information is useful as the gaRequest() function allows for querying multiple GA accounts at one time.
~Figure 10~
Since the Client ID, Client Secret and Refresh Token are needed each session, it is recommended to store these values in your .Rprofile config file as environmental variables named: GAR_CLIENT_ID, GAR_CLIENT_SECRET and GAR_REFRESH_TOKEN. The GAR package is designed to look for and use these variables by default.
Simple! Once initial authentication is made and credentials are saved to your config file it is very easy to refresh the acccess token (refreshToken()) and retrieve data (gaRequest()) on a continual basis.
Enjoy!
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.