RGoogleAnalytics with floating date

If you want to get data from Google Analytics via RGoogleAnalytics from last week or last month. You have to change fix date as “2016–02–01” to floating date. Can you paste this date directly to code? Of course — you can. However if you scheduled your script via Cron, you have to change date dynamically.

Use Lubridate library

library(lubridate)

Set First and Last day of Last Month

currentDate <-Sys.Date() #current date
# end of previous month:
eopm <- as.character(currentDate - days(day(currentDate)))

# start of previous month:
sopm <- currentDate - days(day(currentDate))
sopm <- as.character(sopm - days(day(sopm) - 1))

Set First and Last day of Last Week

currentDate <-Sys.Date() #current date
# end of previous week
eopw <- as.character((currentDate - days(wday(currentDate))+1))

# start of previous week:
sopw <- currentDate - days(wday(currentDate))
sopw <- as.character(sopw - days(wday(sopw) - 2))

Get GA data

library(RGoogleAnalytics) 
client.id <- "xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"
client.secret <- "xxxxxxxxxxxxxxxd_TknUI"
token <- Auth(client.id,client.secret)
save(token,file="./token_file") # Save the token object for future sessions

query.list <- Init(start.date = sopm,
end.date = eopm,
dimensions = "ga:date",
metrics = "ga:sessions,ga:users",
max.results = 20000,
sort = "ga:sessions",
table.id = profile_id)