動機

利用goole趨勢分析可以了解關鍵詞或主題的搜索趨勢,提供市場洞察和決策制定的參考依據。而我選的主題是跟世足相關,分析臺灣對全球體育盛事的興趣和關注程度。

程式說明

  • 設定關鍵字,並將地區設為台灣
  • 透過gtrendsR包中的countries獲取ountry_code為TW的國家或地區的訊息
  • na.omit刪除缺失值
  • sort()進行排序
  • gprop設為web,使用網路搜索獲取數據,其他的還有新聞、圖片、youtube等可以選
keyword = c("世界盃", "足球","運彩")
geo = "TW"

countries = gtrendsR::countries
geo_code = sort(unique(countries$country_code))
countries_TW = countries[countries$country_code == "TW",]
countries_TW = na.omit(countries_TW)
gprop = "web"
  • 有時無法取到當天 ,因此減1
  • 將時間設定從2010/1/1開始到當日前一天
start_date = "2010-01-01"
end_date = Sys.Date()-1
time = paste(start_date, end_date)
  • 用gtrendsR中的gtrends獲取關鍵字在指定地理位置和時間範圍內的趨勢數據,並存在trends
  • 將trends裡需要的變數都單獨取出,interest_over_time隨時間變化,interest_by_region按地區畫分,interest_by_city按城市畫分,related_queries相關查詢數據
  • 將interest_over_time$hits中小於1的值換成0,可避免出現NA值或警告 -轉換成數值型態
trends = gtrendsR::gtrends(keyword=keyword, 
                           geo=geo, 
                           gprop=gprop, 
                           time=time)

interest_over_time = trends[["interest_over_time"]]
interest_by_region = trends[["interest_by_region"]]
interest_by_city = trends[["interest_by_city"]]
related_queries = trends[["related_queries"]]

interest_over_time$hits[interest_over_time$hits == "<1"] = 0
interest_over_time$hits = as.numeric(interest_over_time$hits)
  • DT創建交互式表格可在r中進行瀏覽

  • reshape2中的dcast可以將長數據與寬數據的相互轉換

  • xts可以處理時間序列數據,因此轉換為xts格式

  • 刪掉data_xts$time

library(dygraphs)
library(xts)

data = data.frame(time=interest_over_time$date, 
                  hits=interest_over_time$hits,
                  keyword=interest_over_time$keyword)

data_df = reshape2::dcast(data,
                          time ~ keyword,
                          value.var="hits")

data_xts = xts(x=data_df,
               order.by=data_df$time)

data_xts$time = NULL
  • 畫圖
fig = dygraphs::dygraph(data_xts) %>% 
  dySeries(keyword[1], color="blue") %>% 
  dySeries(keyword[2], color="red") %>%  
  dySeries(keyword[3], color="green") %>% 
  dyRangeSelector(height=20)

結果

結論

這三個詞都和世足相關,而從結果可以發現人們在世足那段時間,也就是2010年,2014年,2018年和2022年,對這三個詞的搜索較平常還要高得多,而每一屆的世足也被臺灣人漸漸關注,運彩也興起,因此可以從中拓展商機。