How to Connect R to Google Analytics
Connecting R to Google Analytics moves your web data out of the ready-made reports and into a powerful environment where you can conduct custom, in-depth analysis. This guide provides a straightforward, step-by-step process for linking the two, enabling you to build custom reports, perform statistical modeling, and visualize your data in new ways.
Why Connect R to Google Analytics?
While the Google Analytics interface is great for a quick overview of your website's performance, it has its limits. When you need to answer more complex business questions, you often hit a wall. Connecting to GA through R smashes through that wall, giving you direct access to your site’s raw data.
Here are a few reasons why this is a game-changer:
- Deeper Analysis: You can apply advanced statistical methods like regression analysis, time-series forecasting, and correlation analysis to uncover relationships your standard GA report would never show you. For example, you could model how blog traffic impacts product sign-ups.
- Custom Visualizations: Move beyond the default charts in GA. With R packages like
ggplot2, you can create publication-quality graphs and dashboards tailored to your specific needs, telling a clearer story with your data. - Bypass Data Sampling: If you manage a high-traffic website, you’ve likely run into Universal Analytics' data sampling, which can skew your reports. The R connection allows you to automatically break your queries into smaller chunks to avoid sampling and get more accurate results.
- Automated and Reproducible Reporting: You can write an R script once to pull, clean, analyze, and visualize your data. Using tools like R Markdown, you can generate a complete report automatically every week or month, saving hours of manual work.
- Integrate with Other Data: The real power comes when you combine your GA data with other information. Pull data from your CRM, ad platforms like Facebook Ads, or your own customer database and merge it with your web analytics to get a complete picture of your customer's journey.
Getting Started: What You'll Need
Before you dive into writing code, make sure you have the following ready. A little preparation now will save you a lot of headaches later.
- R and RStudio: You’ll need R installed on your machine. We also highly recommend using RStudio, an integrated development environment (IDE) that makes working with R much simpler and more organized.
- Google Analytics Access: You need permission to access the Google Analytics property you want to analyze. Editor-level access is typically required to manage API settings.
- A Google Cloud Platform (GCP) Project: To communicate with Google's APIs, you need to set up a project within the Google Cloud Platform. This is a common requirement for using services like the Google Analytics API and is free for this type of use.
Step-by-Step: Connecting R to the Google Analytics API
Let's walk through the setup process. It involves installing an R package, configuring access in your Google Cloud account, and then authenticating within your R session.
Step 1: Install the googleAnalyticsR package
The first step inside RStudio is to install the best R package for the job. We'll be using googleAnalyticsR, a powerful and well-maintained package that works with both Universal Analytics (UA) and Google Analytics 4.
Open RStudio and run the following command in the console:
install.packages("googleAnalyticsR")
Step 2: Enable the APIs in Google Cloud Platform
Now, head over to the Google Cloud Platform. Your goal here is to tell Google that your application (which is the R script you're about to write) is allowed to request data from the Google Analytics API.
- Create a new project or select an existing one. Give it a memorable name, like "R Reporting Project."
- In the navigation menu, go to APIs & Services > Library.
- Search for "Google Analytics." You will need to enable two separate APIs:
- Click "Enable" for both of them to ensure you can access any type of GA property.
Step 3: Create Authentication Credentials
Next, you need to create credentials so your R script can prove it has permission to access your data.
- In the Google Cloud console, navigate to APIs & Services > Credentials.
- Click + CREATE CREDENTIALS at the top of the screen and choose OAuth client ID.
- When prompted for the Application Type, select Desktop app. This is a critical step – choosing another type will cause authentication errors.
- Give it a name and click CREATE. A pop-up will appear with your Client ID and Client Secret. You can either download the JSON file (the easiest method) or copy these credentials manually.
Step 4: Authenticate from R
With your API access enabled and credentials created, it's time to go back to RStudio to make the connection.
First, load the package you installed:
library(googleAnalyticsR)
Next, run the main authentication function. This function will open a browser window where you'll sign in to your Google Account and grant permission for R to access your GA data.
ga_auth()
Upon running this, a browser tab will open, prompting you to choose a Google account. Select the account that has access to the Google Analytics property you want to use. Follow the prompts to grant the necessary permissions.
Once you’ve successfully authenticated, you’ll be returned to RStudio. A message in your console will confirm that authentication is complete, and a hidden .httr-oauth file will be saved in your working directory to handle future sessions automatically.
Pulling Google Analytics Data into R
Now that you're connected, you can start requesting data. The specific function you use will depend on whether you're working with a Universal Analytics (UA) property or a Google Analytics 4 property.
Step 1: Get Your Property/View ID
First, you need to tell R which GA property to pull from. You can get a tidy list of all the Google Analytics Accounts, Properties, and Views you have access to with one command:
ga_account_list()
This command returns a data frame. Locate the property you want to analyze and note its viewId (for Universal Analytics) or its propertyId (for GA4) from the list. You will need this ID for your data queries.
Step 2: Pulling Data from Universal Analytics
To query a Universal Analytics property, use the google_analytics() function. This function requires your viewId and allows you to specify a date range, metrics, and dimensions.
For example, let's pull the number of users and sessions by date for the last 30 days:
# Replace "YOUR_VIEW_ID" with the actual ID from the account list
my_view_id <- "12345678"
# Pull the data
ua_data <- google_analytics(
viewId = my_view_id,
date_range = c(Sys.Date() - 31, Sys.Date() - 1),
metrics = c("sessions", "users"),
dimensions = "date"
)
# See the first few rows of your new data frame
head(ua_data)You'll now have a clean data frame named ua_data with your GA information, ready for visualization or analysis.
Step 3: Pulling Data from Google Analytics 4
GA4 reporting works a bit differently. The function to use is ga_google_analytics_4(). The syntax is very similar, but it uses the propertyId instead of the viewId.
Here’s how you can pull GA4 sessions and total users by date for the last 30 days:
# Replace "YOUR_PROPERTY_ID" with the actual ID from the account list
my_property_id <- "987654321"
# Pull GA4 data
ga4_data <- ga_google_analytics_4(
property_id = my_property_id,
date_range = c(Sys.Date() - 31, Sys.Date() - 1),
metrics = c("sessions", "totalUsers"),
dimensions = c("date")
)
# Look at the result
head(ga4_data)You did it! Your data is now in R, ready for whatever question you want to throw at it.
Final Thoughts
Connecting R to Google Analytics is one of the most powerful steps you can take to level up your analytics skills. You break free from the limitations of the web interface and gain the ability to conduct truly custom, automated, and repeatable analysis that answers the deep questions specific to your business.
For those who need powerful analytics without writing code, we've built tools like Graphed to simplify this entire process. Instead of setting up APIs and R scripts, you can securely connect Google Analytics, your ad platforms, and CRM in seconds. From there, you just ask questions in plain English - like "Compare traffic and conversions across all my campaigns this month" - and get instant, real-time dashboards that show you what's working so you can get back to growth.
Related Articles
How to Connect Facebook to Google Data Studio: The Complete Guide for 2026
Connecting Facebook Ads to Google Data Studio (now called Looker Studio) has become essential for digital marketers who want to create comprehensive, visually appealing reports that go beyond the basic analytics provided by Facebook's native Ads Manager. If you're struggling with fragmented reporting across multiple platforms or spending too much time manually exporting data, this guide will show you exactly how to streamline your Facebook advertising analytics.
Appsflyer vs Mixpanel: Complete 2026 Comparison Guide
The difference between AppsFlyer and Mixpanel isn't just about features—it's about understanding two fundamentally different approaches to data that can make or break your growth strategy. One tracks how users find you, the other reveals what they do once they arrive. Most companies need insights from both worlds, but knowing where to start can save you months of implementation headaches and thousands in wasted budget.
DashThis vs AgencyAnalytics: The Ultimate Comparison Guide for Marketing Agencies
When it comes to choosing the right marketing reporting platform, agencies often find themselves torn between two industry leaders: DashThis and AgencyAnalytics. Both platforms promise to streamline reporting, save time, and impress clients with stunning visualizations. But which one truly delivers on these promises?