Created
September 28, 2016 07:45
-
-
Save IronistM/83ef45f7b5bf1f6b73f00cd691b68f1f to your computer and use it in GitHub Desktop.
R Script to read basic info from all available views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library("RGoogleAnalytics") | |
library("ggplot2") | |
library("dplyr") | |
#Google Auth Codes | |
clientid = "USE YOUR CLIENT ID HERE" | |
clientsecret = "CLIENT SECRET GOES HERE" | |
#Fire off an AUTH request to Google. This will actually kick off a browser opening to do the OAuth2 transaction. | |
oauth_token <- Auth(clientid,clientsecret) | |
#Save your token to the filesystem. | |
save(oauth_token, file="oauth_token") | |
#This loads the token from the filesystem (So for iterations 2-, you start here) | |
load("oauth_token") | |
#Helper funtion to make sure your token is (still) valid. | |
ValidateToken(oauth_token) | |
#Function to pull list of available Views and View IDs available to Authenticated User. | |
#These are put into the dataframe "GAProfiles" | |
GAProfiles <- GetProfiles(oauth_token) | |
#How many views do I have access to? | |
nrow(GAProfiles) | |
#Duplicate GA Profiles | |
ds.profiles <- GAProfiles | |
#Add zeroed columns for sessions and pageviews | |
ds.profiles$sessions <- 0 | |
ds.profiles$pageviews <- 0 | |
#Create a list of the View IDs | |
idlist = GAProfiles$id | |
#Iterate through them and pull a month's worth of sessions and pageviews. Append data to each row of ds.profiles. | |
for (id in idlist) { | |
tableid = paste("ga:", id) | |
query.list <- Init(start.date = "2015-02-01", | |
end.date = "2015-03-02", | |
dimensions = "ga:year", | |
metrics = "ga:sessions,ga:pageviews", | |
# sort = c("ga:date", "-ga:pageviews"), | |
# filter = "ga:medium==organic;ga:source==google", | |
# segments = "", | |
# max.results = 5000, | |
# start.index = 1, | |
table.id = tableid) | |
query <- QueryBuilder(query.list) | |
ga.temp <- GetReportData(query, oauth_token) | |
ds.profiles$sessions[ds.profiles$id==id] <- ga.temp$sessions[1] | |
ds.profiles$pageviews[ds.profiles$id==id] <- ga.temp$pageviews[1] | |
} | |
# Use dplyr to sort and filter the datatable for views with actual traffic | |
ds.profiles <- ds.profiles %>% | |
filter(sessions>0) %>% | |
arrange(-sessions) | |
#Bar plot all views with at least one session that month. | |
ggplot(ds.profiles, aes(x=name, y=sessions)) + | |
geom_bar(stat='identity') + | |
coord_flip() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment