用 R 分析社交媒体数据
Sowmya Vivek
Data Science Coach
screen_name 存储用户的账号名
rtweet 库将 Twitter JSON 转为数据框
# 使用 search_tweets() 抓取 "#brexit" 推文
tweets_df <- search_tweets("#brexit")
# 查看列名
names(tweets_df)

screen_name 了解用户兴趣followers_count 比较社交影响力retweet_count 和 text 找出热门推文screen_name 指 Twitter 账号名(句柄)# 使用 search_tweets() 抓取 "#Arsenal" 推文
twts_arsnl <- search_tweets("#Arsenal", n = 18000)
# 生成该话题的用户及发推次数表
sc_name <- table(twts_arsnl$screen_name)
head(sc_name)
_____today_____ ___JJ23 ___SAbI__ __ambell __Amzo__ __bobbysingh
1 2 3 1 1 1
# 按发推次数降序排序
sc_name_sort <- sort(sc_name, decreasing = TRUE)
# 查看前 6 位用户及频次
head(sc_name_sort)
_whatthesport footy90com Official_ATG1 TheShortFuse RubellM ArsenalZone_Ind
176 90 88 53 48 43
# 用 lookup_users() 获取用户数据
tvseries <- lookup_users("GameOfThrones", "fleabag", "BreakingBad")
# 创建仅含 screen_name 与 followers_count 的数据框
user_df <- tvseries[,c("screen_name","followers_count")]
# 查看关注者数以便比较
user_df
screen_name followers_count
<chr> <int>
GameOfThrones 8597188
fleabag 58727
BreakingBad 1240349
retweet_count 存储转推次数# 构建包含推文文本与转推数的数据框
rtwt <- tweets_arsenal[,c("text", "retweet_count")]
# 按转推数降序排序
library(dplyr)
rtwt_sort <- arrange(rtwt, desc(retweet_count))
# 去除重复文本的行
rtwt_unique <- unique(rtwt_sort, by = "text")
# 输出转推次数最高的前 6 条去重帖子
head(rtwt_unique)
retweet_count text
<int> <chr>
5606 Once a Gunner, Always a Gunner. We are proud of you @alexanderiwob
3764 Emirates on Fire 🔥🔥🔥🔥 Never give up Gunners💪🏽💪🏽💪🏽 #Arsenal #CO
2798 That mood tonight ⚡️⚡️⚡️ 3️⃣ POINTS 🔴⚪️ #Arsenal #Gunners #COYG h
2741 #Arsenal fan: "I reckon we'll win the League this season." @Robbie
1687 Auba 😭😭😍😍 This is what I call happiness #aubameyang #arsenal
1166 When sky sports introduced the new Monday night football! The Sha
用 R 分析社交媒体数据