anoop
anoop

Reputation: 1614

RGoogleAnalytics different browser page view as different row

We have used the RGoogleAnalytics library from R. We have used the sample code google has provided for testing. So our init is like

query.list<-Init(start.date = "2015-01-01",
             end.date = "2015-07-28",
             dimensions = "ga:year,ga:month,ga:browser",
             metrics = "ga:pageviews",
             max.results = 10000,
             #sort = "ga:year",
             table.id = "ga:xxxxx")
ga.query <- QueryBuilder(query.list)
ga.data <- GetReportData(ga.query, token)

After complete this and print the result we are getting the result like (format 1 below)

    **Year  Month   Browser              Pageviews**
1   2015    1       Amazon Silk             1
2   2015    1       Android Browser         4
3   2015    1       Chrome                  506
4   2015    1       Firefox                 157
5   2015    1       Internet Explorer       365
6   2015    1       Opera                   1
7   2015    1       Safari                  192
8   2015    1       Safari (in-app)         1

We are getting a format above. but instead i need to get the data like the different browser should be in different row like (format2 below)

**Year  Month   ie  firefox  chrome**

  2015   1     365   157       506

Can we able to print the values like in the format2 using the RGoogleAnalytics functions? Or do we have the any formatting method in R to convert the data from format1 listing to format2 listing

Also is there any option in RgoogleAnalytics to print 0 under a browser if there is no pageview under that browser on a particular month.

Upvotes: 2

Views: 96

Answers (1)

enlego
enlego

Reputation: 320

You need to transform the data frame from long (all the browsers in one column) to wide (each browser in a new column). This can be easily done with the package reshape2. The function you need is dcast().

You can install the package with:

install.packages("reshape2")

and then load it with:

library(reshape2)

The usage of dcast() function is:

wideDataFrame <- dcast(longDataFrame, idVariableColumn1 + idVariableColumn2 ~ variableColumn, value.var="Name of column with the measurement values")

where

  • wideDataFrame is your resulting data frame
  • longDataFrame is the previous data frame (the one you have right now)
  • idVariableColumn1 is the column that has to remain as a factor column
  • idVariableColumn2 is another column to remain as a factor
  • variableColumn is the colum you want to "open" in new columns
  • and value.val = "name blablabla" is your column with values.

in your case

dataWide <- dcast(ga.data, Year + Month ~ Browser, value.var="Pageviews")

You can reshape back your data from wide to long (the opposite as we did here) with the function melt().

Upvotes: 2

Related Questions