Lourdes Hernández Lourdes Hernández - 4 years ago 271
R Question

Get a custom dimension dynamically from Google Analytics API

Is there a way of getting data from GA API, including a custom dimension in a dynamic way?

I run this code:

startDate="YYYY-MM-DD"
endDate="YYYY-MM-DD"
viewID="ga:XXXXXXXX"
dim=XX

query.list<-Init(
start.date=startDate,
end.date=endDate,
dimension="print(paste0('ga:dimension',dim), quote=FALSE), ga:date",
metrics="ga:sessions",
sort="-print(paste0('ga:dimension',dim), quote=FALSE)",
max.results=10000,
table.id=viewID
)

ga.query<-QueryBuilder(query.list)
ga.data<-GetReportData(ga.query,token,paginate_query = T, split_daywise = T)


and the output is:

Error in ParseDataFeedJSON(GA.Data) :
code : 400 Reason : Invalid value 'print(paste0('ga:dimension',dim),quote=FALSE),ga:date'. Values must match the following regular expression: '(ga:.+)?'

Thanks in advance!

Answer Source

Lourdes, you write print&paste functions between " ", Init function reads them as character, not as a function. Try this:

startDate="YYYY-MM-DD"
endDate="YYYY-MM-DD"
viewID="ga:XXXXXXXX"
dim=XX
query.list<-Init(
            start.date=startDate,
            end.date=endDate, 
            dimension=paste(toString(paste("ga:dimension", dim, sep="")), "ga:date",sep=", "),
            metrics="ga:sessions",
            sort=toString(paste("-ga:dimension", dim, sep="")),
            max.results=10000,
            table.id=viewID  
        )

ga.query<-QueryBuilder(query.list)
ga.data<-GetReportData(ga.query,token,paginate_query = T, split_daywise = T)

For custom dimensions 1,5,11 write:

 dim=c("1","5","11")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download