Search code examples
rgoogle-analyticsgoogle-analytics-apigoogle-analytics-firebase

Query multiple Google Analytics view ids using googleAnalyticsR v4 API package


I want to use the new googleAnalyticsR package to extract Google Analytics data using the v4 API.

The documentation (http://code.markedmondson.me/googleAnalyticsR/v4.html) demonstrates the execution of a query using one ga_id, but not using multiple view ids. There is another R package called GAR which permits the execution of multiple view id in a single Google Analytics query, but the googleAnalyticsR package includes v4 API features. I attempted to query multiple view ids using ga_id <- c('viewId','viewId'), but the query returns an error. Is there a way to query multiple view ids using googleAnalyticsR v4 API?


Solution

  • This probably isn't supported in API directly, but given you are using R, this could be very easily achieved using FOR loops. Below is an example where I am querying multiple GA views (1 view = 1 language version of the site):

    viewId <- c(6006393, 79777098, 79781440, 79981805, 75315234, 78174757, 76630182, 79447058)    
    
    ga_data_final <- data.frame()
    
    for (i in viewId) {
      ga_data_temp <- 
        google_analytics_4(i, #=This is a (dynamic) ViewID parameter
                           date_range = c("2014-01-01",
                                          "2016-08-15"), 
                           metrics = c("sessions"), 
                           dimensions = c("yearMonth",
                                          "source",
                                          "medium"),
                           max = -1)
      ga_data_temp$viewId <- i
      ga_data_final <- rbind(ga_data_final, ga_data_temp)
    }
    

    The code above retrieves:

    • 1 metric: number of sessions
    • 3 dimensions: yearMonth, Source, Medium

    It's using 2 dataframes - the master one is created as empty before FOR loop starts. Every FOR cycle pulls rows for 1 view (temporarily stored in ga_data_temp) and once finished, appends them to the master dataframe (ga_data_final).

    Hope this helps.