# source: https://stackoverflow.com/a/46482580/1007029 is_check <- ("CheckExEnv" %in% search()) || any(c("_R_CHECK_TIMINGS_", "_R_CHECK_LICENSE_", "TRAVIS") %in% names(Sys.getenv())) knitr::opts_chunk$set(eval = !is_check, purl = !is_check)
ganalytics provides functions that makes it easy to define filters using natural R language operators. This example shows how to use
ganalytics to define dimension or metric filters that can be used by the
googleAnalyticsR package. The current development version of
googleAnalyticsR supports filters defined with
Once installed, load these packages. Please refer to the
googleAnalyticsR package documentation on configuration steps you may need to complete in order to use the Google Analytics APIs.
library(googleAnalyticsR) library(ganalytics) library(dplyr) library(tidyr) library(ggplot2) library(purrr) library(knitr) ga_auth(file.path("~", "ga.oauth")) view_id <- "117987738" start_date <- "2018-05-01" end_date <- "2018-06-30"
In this example, we'll define the following filters: Device category is desktop or tablet - a dimension filter using an OR condition. New visitors using either a desktop or tablet device - a dimension filter involving both an AND and an OR condition. * At least one goal completion or transaction - a metric filter using an OR condition.
The above list of filters will be defined using
ganalytics expressions as follows:
# Device category is desktop or tablet - a dimension filter using an OR condition. desktop_or_mobile <- Expr(~deviceCategory == "desktop") | Expr(~deviceCategory == "tablet") # New visitors using either a desktop or tablet device - a dimension filter involving both an AND and an OR condition. new_desktop_and_mobile_visitors <- Expr(~userType == "new") & desktop_or_mobile # At least one goal completion or transaction - a metric filter using an OR condition. at_least_one_conversion <- Expr(~goalCompletionsAll > 0) | Expr(~transactions > 0)
We can now use
results <- google_analytics( viewId = view_id, date_range = c(start_date, end_date), metrics = c("users", "sessions", "goalCompletionsAll", "transactions"), dimensions = c("deviceCategory", "userType"), dim_filters = new_desktop_and_mobile_visitors, met_filters = at_least_one_conversion )
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.