Hi! In this tutorial, I’ll show you how to get unsampled data from google analytics with R language library googleAnalyticsR from Mark Edmondson.

You will need

How to

  1. Enable Analytics API in google cloud console, create project if you have’t. Enable Analytics API

  2. Create service account key. Create service account

  3. Add service account client_email to Google Analytics. Admin -> Account (User Management) -> Add service account email.

  4. Write script in Rstudio.

 options(googleAuthR.scopes.selected = c("https://www.googleapis.com/auth/analytics")) # Add options for working with google analytics api

 library(googleAuthR) # Help auth to google analytics      
 library(googleAnalyticsR) # Connect library for  working with google analytics

 gar_auth_service("googleAnalytics.json") # Add auth token
 gaId <- "youId" # View ID in google analytics

 from <- Sys.Date() - 2
 to <- Sys.Date() - 1

 ga <-
  google_analytics_4(
    gaId,
    date_range = c(from, to),
    metrics = c("pageviewsPerSession", "sessionDuration"),
    dimensions = c("date", "sourceMedium", "keyword"),
    anti_sample = TRUE
  )