· 9 years ago · Sep 28, 2016, 12:14 PM
1library("RGoogleAnalytics")
2library("ggplot2")
3library("dplyr")
4
5#Google Auth Codes
6clientid = "USE YOUR CLIENT ID HERE"
7clientsecret = "CLIENT SECRET GOES HERE"
8
9#Fire off an AUTH request to Google. This will actually kick off a browser opening to do the OAuth2 transaction.
10oauth_token <- Auth(clientid,clientsecret)
11
12#Save your token to the filesystem.
13save(oauth_token, file="oauth_token")
14
15#This loads the token from the filesystem (So for iterations 2-, you start here)
16load("oauth_token")
17
18#Helper funtion to make sure your token is (still) valid.
19ValidateToken(oauth_token)
20
21#Function to pull list of available Views and View IDs available to Authenticated User.
22#These are put into the dataframe "GAProfiles"
23GAProfiles <- GetProfiles(oauth_token)
24
25#How many views do I have access to?
26nrow(GAProfiles)
27
28#Duplicate GA Profiles
29ds.profiles <- GAProfiles
30
31#Add zeroed columns for sessions and pageviews
32ds.profiles$sessions <- 0
33ds.profiles$pageviews <- 0
34
35#Create a list of the View IDs
36idlist = GAProfiles$id
37
38#Iterate through them and pull a month's worth of sessions and pageviews. Append data to each row of ds.profiles.
39for (id in idlist) {
40 tableid = paste("ga:", id)
41 query.list <- Init(start.date = "2015-02-01",
42 end.date = "2015-03-02",
43 dimensions = "ga:year",
44 metrics = "ga:sessions,ga:pageviews",
45 # sort = c("ga:date", "-ga:pageviews"),
46 # filter = "ga:medium==organic;ga:source==google",
47 # segments = "",
48 # max.results = 5000,
49 # start.index = 1,
50 table.id = tableid)
51 query <- QueryBuilder(query.list)
52 ga.temp <- GetReportData(query, oauth_token)
53 ds.profiles$sessions[ds.profiles$id==id] <- ga.temp$sessions[1]
54 ds.profiles$pageviews[ds.profiles$id==id] <- ga.temp$pageviews[1]
55}
56
57# Use dplyr to sort and filter the datatable for views with actual traffic
58ds.profiles <- ds.profiles %>%
59 filter(sessions>0) %>%
60 arrange(-sessions)
61
62#Bar plot all views with at least one session that month.
63ggplot(ds.profiles, aes(x=name, y=sessions)) +
64 geom_bar(stat='identity') +
65 coord_flip()