Open MarkEdmondson1234 opened 6 years ago
This could be a basic example - write a group of GA fetches to one CSV file:
## setup
library(googleAnalyticsR)
library(tidyverse)
# names the auth file so you can reuse it later
ga_auth("ga.auth")
viewIds <- c(12345678, 23456789, 34567891, 45678912)
# function to map over the viewID data fetches
get_ga_data <- function(viewId){
google_analytics(viewId,
#yyyy-mm-dd
date_range = c("2017-11-01","2018-10-31"),
metrics = c("metric1"),
dimensions = c("dimension1","dimension2"),
anti_sample = TRUE
)
}
list_of_gadata <- map(viewIds, get_ga_data)
# name the list of data.frames so you know which viewId they are
list_of_gadata <- setNames(list_of_gadata, viewIds)
# function to process each data.frame
process_ga <- function(x){
x %>%
mutate(transactionRevenue = if(is.null(transactionRevenue)) 0 else transactionRevenue,
transactionId = if(is.null(transactionId)) "NA" else transactionId,
dimension01 = if(is.null(dimension01)) "NA" else dimension01
)
}
## process all the data.frames
list_of_gadata_processed <- map(list_of_gadata, process_ga)
name_to_col <- function(the_name, the_obj){
# get the right object from the list
o <- the_obj[[the_name]]
o %>%
mutate(viewId = the_name)
}
# could do this in a lookup if a lot of them, otherwise in same order as viewIds
view_names <- c("View1","View2","View3","View4")
## put the viewId into a column of the data.frames
finished_list <- map(viewIds, ~name_to_col(.x, the_obj = list_of_gadata_processed))
# combine data.frames and write to csv
all_data <- finished_list %>%
reduce(bind_rows) %>%
write_csv("data/place_to_save.csv")
I asked on Twitter/Slack for examples, here were some suggestions: