Table of contents
- What is R programming language
- Important terms
- Examples of code from the article
- Installing the R Language
- What are packages in R
- Installing packages in the R language
- Obtaining detailed information on how to work with the package functions
- RAdwords. A package for working the Google AdWords API
- How to work with the AdWords API
- What you need for working with RAdwords
- Main functions of the RAdwords package
- Examples of code to get data from Google AdWords, using RAdwords
- More examples of working with RAdwords
What is the R Programming Language and How to Use It for Working with the APIs of Google AdWords
Alexey Seleznev, Head of Analytics Department at Netpeak
Viktor Osadchiy, Creative Writer at OWOX BI
If you run a number of small ad campaigns in a single account, you only need to check the necessary data in Google AdWords and Analytics. However, if you use the same way to roughly estimate the performance of a couple douzens ad campaigns in multiple accounts, you’ll spend at least a few hours. The detailed analysis will take you days and even weeks, while you’ll be spending your marketing budget without knowing if you do it effectively or not.
In this article I’ll tell you how to automate working with the data from Google Analytics, by using the package that enhance the basic capacities of the R programming language.
Below I explain everything simply and clearly, to be understood by any user that hasn’t ever written any code. To understand the content of the article you only need to know what is a function in the context of Microsoft Excel or Google Spreadsheets. Warning! This article may trigger you to start learning the R language.
grow 22% faster
Grow faster by measuring what works best in your marketing
Analyze your marketing efficiency, find the growth areas, increase ROIGet demo
What is R programming language
R is a programming language and free software environment for statistical computing and graphics. This is the R language definition from Wikipedia.
R was created by Robert Gentleman and Ross Ihaka, two employees of the Oakland University. The language was named after the first names of the R creators.
There’s a number of terms that are often used in the article. To make things clear, I’ll give a couple definitions in this part of the article.
Function is a grouped number of commands returning some value or functions in the R language. As mentioned above, functions in the R language are similar to those in MS Excel.
Arguments. Almost any function requests some entering values that will be used to make some actions and calculations. You need to attribute the aforementioned values to function arguments. For example, let’s talk about the VLOOKUP Excel function, and check what its syntax looks like:
=VLOOKUP(Value you want to look up, range where you want to look up the value, the column number in the range containing the return value, Exact Match or Approximate Match — indicated as 0/FALSE or 1/TRUE).
The arguments of the function are all the values you indicate inside the brackets after the function name. The VLOOKUP function requires at least 3 arguments: the value you want to look up, also called the lookup value, the range where the lookup value is located, the column number in the range that contains the return value, and, optionally, you can specify TRUE if you want an approximate match or FALSE if you want an exact match of the return value.
Assignment operator "<-" is used to assign a value to an object. For example, to create an X variable that will contain a value of 10, you need to perform the following command.
X <- 10
Vector in the R language is a named single-dimension array that contains a set of the elements of the same type (numeric, logical or text values that can’t be combined). To create a small length vector, you can use the concatenation function c(). The comma-separated list of values in vector stands for the arguments in the function.
For example, a vector camp_name that contains the names of the ad campaigns can be created this way:
camp_name <- c(“CampName1”, ”CampName2”, “CampName3”, “CampName4”)
DataFrame — is the class of objects in the R language that is similar to tables. DataFrame is actually a set of vectors of the same length, but this is exactly how we see tables that we are used to work with.
Here’s an example of the mtcars frame that is embedded in the language R. The data was imported from the Motor Trend US magazine of 1974. The frame includes fuel burn rate, 10 aspects of car design, and different characteristics for 32 cars (models from 1973 to 1974):
Examples of code from the article
The article contains examples of queries to the APIs of Google AdWords in the R language. You can simply copy-paste the examples from the article or download them from the GitHub repository here.
Installing the R Language
To understand the material from the article better, I recommend that you execute all of the provided examples of code on your PC. Let’s start with installing the R language.
R is a cross-platform language. You can install it on Windows, MacOS and Unix operating systems.
The installation process is the same as installing a program, and it doesn’t require any special settings. You simply need to follow this link, choose your operating system, then download and install the R language on your PC.
What are packages in R
For now, the R language has obtained quite a big community of users and developers. Many of them create their own R packages to enhance the R language capacities.
Package in R language is a module that contains a number of functions and a set of data. The main repository for the R packages is CRAN. At the moment of writing this paragraph, there are 12,148 packages in R. Along with CRAN, users upload a lot of packages on GitHub, available to the public. As a rule, you can find the latest versions of packages from developers, while the number of repositories in the R language is more than 80,000.
Installing packages in the R language
Before using any functions or data sets from a package, you need to install it. To install a package from CRAN, you simply need to use a function install.packages, specifying the package name.
Let’s install the devtools package.
The devtools package contains a set of functions to create new functions in the R language, as well as to install packages from third-party repositories including GitHub.
As was mentioned above, the latest versions of packages can be found on GitHub, and not in CRAN. Let’s try to install the RAdwords package from GitHub.
To install a package from GitHub in the devtools package, there’s the install_github function. However, the devtools package is not included in the basic R configuration. That’s why you’ll have to use the library command in order to apply the package to the R session.
#Installing the RAdwords package
The function install_github requires just 1 argument: name of the user, author of the repository on GitHub (https://github.com/jburkhardt) and the name of the repository RAdwords (https://github.com/jburkhardt/RAdwords).
Obtaining detailed information on how to work with the package functions
Any package in R and any function of a package have a detailed information describing each argument, working with functions, and the examples of the function use.
To get a list of the package functions, along with the explanation of what the function does, you can use the help command and send the necessary package name in the package argument. For example, to get information on the RAdwords functions, execute the following command:
help(package = «RAdwords»)
You’ll open an html page with this content:
If you only need info on a definite function, add its name to the help command. For example, to get information on the doAuth function, apply the RAdwords package using the library function and execute help:
RAdwords. A package for working the Google AdWords API
Author: Johannes Burkhardt
How to install: devtools::install_github(’jburkhardt/RAdwords’)
How to work with the AdWords API
Google AdWords has a broad interface of 49 reports, for uploading data from your ad account. At first, you may find it a little complicated to find a necessary report. The official documentation provides the following table, to make looking for a necessary report easier:
Each report consists of its own set of fields which can be attributes, segments and metrics.
Attributes are fields, measurements or parameters, that contain information about some settings or constants that don’t change the grouping of the required data. For example, such account settings as currency (field AccountCurrencyCode) don’t change the number of lines from the Campaign Performance Report.
Segments are also parameters, but they change the grouping structure. For example, if you request data from the Campaign Performance Report with the Date field, the requested data about the campaign efficiency will be grouped by date.
Metrics are quantity indicators such as clicks, views, summary of spent money, etc.
Using the RAdwords package, you can address any of the reports and request the available fields from the report without getting to deep into how to form and send HTTP queries to the API service, as well as without studying every interface detail of the API.
What you need for working with RAdwords
To start working with the RAdwords package, you’ll need access to the Google AdWords API. Here’s a link with more detailed information.
To set up access to the API, you’ll need an identifier and a secret key from the OAuth2 client. By the OAuth2 client I mean a client app, but not the AdWords MCC account AdWords.
- Log in to your managing account and navigate to "Credentials" in the Google Developers Console.
- In the dropdown menu, choose "Create project", then name the project and click "Create".
- Choose "Create Credentials", next "OAuth client ID".
- Click "Configure consent screen" and fill in the necessary fields. Save changes to get back to the "Credentials" screen.
- Choose "Other" in the Application type menu and enter a name in the field you see.
- Click "Create" and you’ll see the client ID and the secret key of the OAuth2 client. Copy them and save them, as you will need this information in the next step to be added to the configuration file.
Main functions of the RAdwords package
RAdwords doesn’t really have many functions. Here’s the list of main ones:
- doAuth is the authentication in the API. To run this function, you’ll need the AdWords API developer token, Client ID and Client Secret credentials that you received in Google Console.
- reports returns the vector of available reports in the API according to your query.
- metrics returns the vector of available fields in the report according to your query.
- statement is the preparation of the query to the AdWords API.
- getData is sending a query and obtaining data from the API.
Examples of code to get data from Google AdWords, using RAdwords
#Activating the package library(RAdwords) #Authentication adwords_auth <- doAuth() account_id <- “000-000-0000” #ID of your AdWords account #Preparing the query #Getting data for the last 30 days #Function format.Date changes the data from the standard format 2017-01-01 to 20170101 body <- statement(select=c('Date', 'CampaignName', 'CampaignId', 'AccountCurrencyCode', 'Impressions', 'VideoViews', 'Clicks', 'Interactions', 'AllConversions', 'Cost'), report="CAMPAIGN_PERFORMANCE_REPORT", start=format.Date(Sys.Date() - 31, "%Y%m%d"), end=format.Date(Sys.Date() - 1, "%Y%m%d")) #Requesting data AdwData <- getData(clientCustomerId = account_id, google_auth = adwords_auth, statement = body, transformation = T)
The statement function forms the body of the query. In the select argument you send the names of all the required fields, with the names presented in the form of a vector. You need to use the report argument to send the name of the report, then the start and end arguments to send the reporting period.
Remember to use the YYYYMMDD format of dates. By default, the date format in R is YYYY-MM-DD. You can send the dates either as lines or transform any date using the format.Date function as in the aforementioned example.
The getData function queries the clientCustomerId argument for the number of the ad account in the format of 000-000-0000.
At the beginning of the script we created an adwords_auth variable. We used the doAuth function to send the credential data for the access to the Google AdWords API. You need to send the saved credential data to the google_auth argument, using the getData function.
Next, you’ll have to send the query body, created using the statement function, to the statement argument.
Having executed all of the aforementioned code, you’ll get the AwData object in your operational environment. The object will contain a table (Data frame) with all of the information queried from the API.
More examples of working with RAdwords
The R language can help you automate working with the statistic data from many sources including any ad systems and web analytics platforms. There’s a variety of ready-to-use packages to enhance the basic R capacities.
Choosing the correct package will help you avoid weeks of studying documents on the APIs of ad services, as 90% of work has already been done by someone before. The only thing you’ll have to do, is find the necessary functions in the chosen package and study their main arguments.
Good luck with automating your work with statistics and studying the R language! If you have any questions or need a bit of advice, feel free to leave a comment ;)