--- GA: UA-159972578-2 --- ###### tags: `R` `GA` `googleAnalyticsR` `API` # googleAnalyticsR 套件介紹 ## 1. 授權R使用GA帳號 ```{r} 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 ``` ![](https://i.imgur.com/aZgXFSu.png) ## 2. 選擇帳號裡的資源/檢視 ```{r} my_accounts <- ga_account_list() # GA account內所有資源列表 View(my_accounts) # 查看帳號擁有的資源/檢視 my_id <- 123456789 # 紀錄要使用的網站viewId ``` ## 3. 查詢資料 注意!因為是免費版,一次只能Query 1000筆資料。 但是仍能通過設定時間、抽樣方式,取得一個時段的連續資料(好比爬蟲),因此還是很powerful的。 ```{r} 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")) ``` + 指標(Metrics)/維度(Dimensions)的變數命名請參考:[Dimensions & Metrics Dictionary](https://ga-dev-tools.appspot.com/dimensions-metrics-explorer/) + 看更多套件的功能請參考: [R_documentation](https://www.rdocumentation.org/packages/googleAnalyticsR/versions/0.4.2/topics/google_analytics) ## 4. 開始分析 【範例】分析從4/26~4/30每日流量來源的媒體,並以長條圖的方式呈現。 ```{r} 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) ``` ![](https://i.imgur.com/dYi4hYv.png)