R Language stands out as a programming language meticulously crafted for computational statistics and intricate graphics. Championed by the dedicated R Core Team and the esteemed R Foundation for Statistical Computing, it boasts an extensive collection of packages tailored to address virtually every quantitative or statistical need imaginable.
These encompass an array of applications, spanning from neural networks and nonlinear regressions to phylogenetics and sophisticated plotting capabilities.
In our previous article, we delved into leveraging the power of GA4 using Python. Now let’s focus our attention on exploring its capabilities within R Language and how it works with Google Analytics.
Access it for download on GitHub: https://github.com/Impesud/machine-learning-with-R/blob/main/google-analytics-data/google-analytics-data.R
1
2
3
4
5
6
7
8
9
|
# Google Analytics 4 API with R
# Visit my profile: https://github.com/impesud
# Install googleAnalyticsR v1.1.0
install.packages("googleAnalyticsR")
library(googleAnalyticsR)
library(scales)
library(ggplot2)
|
1
2
3
|
# Authenticate with client OAUTH credentials
# Go to Google Cloud, then 'APIs & Services' -> 'Credentials' and create it
googleAuthR::gar_set_client(json = "here_put_your_path_file_json")
|
1
2
3
4
|
# Provide the service account email and private key
# Go to Google Cloud, then 'IAM and Administration' -> 'Service Account' and create it
ga_auth(email = "here_put_your_service_account_email",
json_file = "here_put_your_other_path_file_json")
|
1
2
|
# Get a list of all GA4 metrics
metrics_list = ga_meta(version = "data")
|
1
2
|
# Set up GA property ID
property_id = "your_property_ID"
|
1
2
3
4
5
6
7
|
# Test API is working
basic <- ga_data(
property_id,
metrics = c("activeUsers", "sessions"),
date_range = c("2023-12-01", "2023-12-31")
)
print(basic)
|
1
2
3
4
5
6
7
8
9
|
# Prepare the data to export to CSV
df <- ga_data(
property_id,
metrics = c("activeUsers","sessions"),
dimensions = c("date","city"),
date_range = c("2023-12-01", "2023-12-31"),
orderBys = ga_data_order(+date)
)
print(df)
|
1
2
|
# Export to CSV
write.csv(df, "here_put_your_path_and_name_of_your_new_CSV_file", row.names=FALSE)
|
1
2
3
4
5
|
#Graph of the required data
ggplot(df, aes(date, activeUsers)) + geom_line() +
xlab("") + ylab("Active Users") + theme_bw() +
scale_y_continuous(labels = label_number(accuracy = 1)) +
ggtitle("Active Users in December 2023")
|