從原始資料建立圖形

案例研究:R 的網路分析

Edmund Hart

Instructor

探索資料

  • 資料涵蓋數天內提到 #rstats 的所有推文
  • 建立圖形的關鍵屬性:
    • screen name(帳號)
    • 推文原始文字
案例研究:R 的網路分析

推文結構解析

  1. ReecheshJC: 「Hey #rstats,我要怎麼做 fct_lump,但依欄位中的計數值來分組?」
  2. kom_256: 「RT @elenagbg: Retweeted R-Ladies Madrid (@RLadiesMAD):\n\nEn el #OCSummit17... Fast Talks sobre #rstats organizado por... https://t.co/CKY5aG…」
案例研究:R 的網路分析
library(igraph)
library(stringr)
raw_tweets <- read.csv("datasets/rstatstweets.csv", 
  stringsAsFactors = FALSE)

資料範例,單筆紀錄

user_name:    Karen Millidine
screen_name:    KJMillidine
tweet_tex:t    RT @Rbloggers: RStudio v1.1 Released 
https://t.co/kCMHc689nY #rstats #DataScience
favorites:    0
retweets:    96
location:    None
expanded_url:    https://wp.me/pMm6L-ExV
in_reply_to_tweet_id:    NA
in_reply_to_user_id:    NA
dt:    10/10/17
案例研究:R 的網路分析

建立圖形

## 取得所有 screen name
all_sn <- unique(raw_tweets$screen_name)

## 建立圖形
retweet_graph <- graph.empty()

## 將 screen name 加為節點
retweet_graph <- retweet_graph + vertices(all_sn)
案例研究:R 的網路分析

建立圖形

## 逐筆取名並新增邊
for(i in 1:dim(raw_tweets)[1]){

# 取出轉推對象名稱 rt_name <- find_rt(raw_tweets$tweet_text[i]) # 若有名稱則加入一條邊 if(!is.null(rt_name)){
# 確認節點是否存在;若無,則新增 if(!rt_name %in% all_sn){ retweet_graph <- retweet_graph + vertices(rt_name) }
# 新增邊 retweet_graph <- retweet_graph + edges(c(raw_tweets$screen_name[i], rt_name))
}
}
案例研究:R 的網路分析

清理圖形

## 計算度數為 0 的節點數
sum(degree(retweet_graph) == 0) 

## 修剪並簡化
retweet_graph <- simplify(retweet_graph)
retweet_graph <- delete.vertices(retweet_graph, 
  degree(retweet_graph) == 0)
案例研究:R 的網路分析

一起來練習吧!

案例研究:R 的網路分析

Preparing Video For Download...