Updated: October 31, 2025
This article introduces how to connect to Google Analytics 4 using R to extract data, using direct authorization via a web page instead of obtaining the key through the console.
Install and load the googleAnalyticsR package
install.packages(c("googleAnalyticsR")
library(googleAnalyticsR)
Authorize
Google OAuth is used here (recommended, no service account required, more convenient):
# Automatic pop-up login to Google account ga_auth()
An authorization window will pop up in your browser; simply click to authorize.
Get Data
Execute the following code to retrieve data for the last 7 days:
# ←← Replace your Property ID←←
PROPERTY_ID <- "206759202"  
# Retrieve raw data (returns a data.frame)
raw_data <- ga_data(
  propertyId = PROPERTY_ID,
  date_range = c("7daysAgo", "yesterday"),
  metrics = "activeUsers",
  dimensions = "date"
)
# Manually process dates + sort
# Conversion date: From "20251024" → "2025-10-24"
raw_data$date <- as.Date(raw_data$date, format = "%Y%m%d")
# Sort by date in ascending order
raw_data <- raw_data[order(raw_data$date), ]
# Output results
print(raw_data)




