Skip to content

Instantly share code, notes, and snippets.

@robertsky
Created December 26, 2015 11:37
Show Gist options
  • Save robertsky/222dee516fe04e9e415e to your computer and use it in GitHub Desktop.
Save robertsky/222dee516fe04e9e415e to your computer and use it in GitHub Desktop.
30 days look back from Google Analytics.
setwd("~/Documents/R/")
require(dplyr)
require(RGoogleAnalytics)
# Authorize the Google Analytics account
# This need not be executed in every session once the token object is created
# and saved
token <- Auth(client.id,client.secret)
# Save the token object for future sessions
save(token,file="./token_file")
ValidateToken(token)
results <- NULL
counter <- 1
# grabbing data from csv file
wpData = read.csv('alvinology_2015_post_list.csv', header = TRUE)
wpData$post_date <- as.Date(wpData$post_date, '%Y-%m-%d')
wpData$end_date <- as.Date(wpData$post_date, '%Y-%m-%d') + 29
i <- sapply(wpData, is.factor)
wpData[i] <- lapply(wpData[i], as.character)
by(wpData, 1:nrow(wpData), function(x) {
print(as.character(x['permalink']))
query.list <<- Init(start.date = as.character(format(x['post_date'], '%Y-%m-%d')),
end.date = as.character(format(x['end_date'], '%Y-%m-%d')),
metrics = paste0("ga:sessions,ga:pageviews"),
filters = paste0("ga:pagePath=~", as.character(x['permalink']), "*"),
table.id = "ga:83136139")
ga.query <- QueryBuilder(query.list)
ga.data <- GetReportData(ga.query, token)
x$sessions = ga.data$sessions
x$pageviews = ga.data$pageviews
if(is.null(results)) {
results <<- x
} else {
results <<- rbind(results, x)
}
if(counter%%100==0) {
ValidateToken(token)
}
counter <<- counter + 1
Sys.sleep(1)
})
write.csv(file='results.csv', x=results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment