Try   HackMD
tags: R GA googleAnalyticsR API

googleAnalyticsR 套件介紹

1. 授權R使用GA帳號

library(googleAnalyticsR)
ga_auth() # This will open a webpage, plz log into your Google Analytics account and paste the athorize code in your R console
1 # Select the current account for analysis

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

2. 選擇帳號裡的資源/檢視

my_accounts <- ga_account_list() # GA account內所有資源列表
View(my_accounts) # 查看帳號擁有的資源/檢視

my_id <- 123456789 # 紀錄要使用的網站viewId

3. 查詢資料

注意!因為是免費版,一次只能Query 1000筆資料。
但是仍能通過設定時間、抽樣方式,取得一個時段的連續資料(好比爬蟲),因此還是很powerful的。

google_analytics(
  my_id, 
  date_range = c("2018-01-01", "2018-12-31"),
  samplingLevel = "SMALL",
  metrics = c("sessions", "users", "pageviews", "bounceRate"),
  dimensions = c("date", "source", "medium", 
		 "landingPagePath", "pagePath",
		 "hour","minute"))

4. 開始分析

【範例】分析從4/26~4/30每日流量來源的媒體,並以長條圖的方式呈現。

df %>% 
  count(date, sessions, medium) %>% 
  mutate(sessions = sessions*n) %>% 
  ggplot(data=df, aes(x=date, y=sessions, fill=medium)) +
  geom_col(show.legend = F) -> p
ggplotly(p)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →