推特:一次获得多个用户的关注者

Twitter: Get followers from multiple users at once

我正在做一个项目,我需要找到一些社交活动的影响范围。我想知道有多少人在丹麦的一个名为 Tinderbox 的节日上接触到评论。 我所做的是获取 Twitter 上的状态,包括丹麦语中的单词 "tinderbox"。然后我想从这些网名中提取关注者的数量。所以我的代码的第一部分是:

library("twitteR")
setup_twitter_oauth(consumer_key,consumer_secret,access_token,access_secret)
1
#get data
TB<-searchTwitter("tinderbox", lan="da", n=10000)
#put into a dataframe
df <- do.call("rbind", lapply(TB, as.data.frame))

我的想法是使用与下面示例中相同的输出,即 直接从推特数据中获取 followersCount。 该示例可在 Whosebug 上找到。但是我不知道怎么做才能达到我的目的(fetching large number of followers and followees in R)

library(twitteR)
user <- getUser("krestenb")
followers <- user$getFollowers()
b <- twListToDF(followers)
f_count <- as.data.frame(b$followersCount)
u_id <- as.data.frame(b$id)
u_sname <- as.data.frame(b$screenName)
u_name <- as.data.frame(b$name)
final_df <- cbind(u_id,u_name,u_sname,f_count)
sort_fc <- final_df[order(-f_count),]
colnames(sort_fc) <- c('id','name','s_name','fol_count')

我的问题是我不能通过从 df$screenName 中提取屏幕名称列表来简单地在 followers <- <- user$getFollowers() 中使用用户名向量。

所以我的想法是,也许我需要对所有不同的屏幕名称进行循环。但是我不知道该怎么做。

我知道我已经描绘了我想要得到的东西,以及我如何 thought/think 我可以到达那里。

非常感谢您的帮助,因为音乐节将于本周末举行。

下面是一些示例代码,它基于您在原始问题中遇到的内容,它将汇总一组用户的 Twitter 结果:

# create a data frame with 4 columns and no rows initially
df_result <- data.frame(t(rep(NA, 4)))
names(df_result) <- c('id', 'name', 's_name', 'fol_count')
df_result <- df_result[0:0,]

# you can replace this vector with whatever set of Twitter users you want
users <- c("krestenb", "tjb25587")                    # tjb25587 (me) has no followers

# iterate over the vector of users and aggregate each user's results
sapply(users, function(x) {
                  user <- getUser(x)
                  followers <- user$getFollowers()
                  if (length(followers) > 0) {        # ignore users with no followers
                      b <- twListToDF(followers)
                      f_count <- as.data.frame(b$followersCount)
                      u_id <- as.data.frame(b$id)
                      u_sname <- as.data.frame(b$screenName)
                      u_name <- as.data.frame(b$name)
                      final_df <- cbind(u_id,u_name,u_sname,f_count)
                      sort_fc <- final_df[order(-f_count),]
                      colnames(sort_fc) <- c('id','name','s_name','fol_count')
                      df_result <<- rbind(df_result, sort_fc)
                  }
              })

要点

我在 df_result 数据框上执行 rbind 时使用了全局赋值运算符 <<-,因此它会 "stick" 在循环之外。正如我在原始答案中提到的,您可以使用 sapply 函数迭代用户向量。在循环内,结果被汇总。

我用包含 Twitter 用户的向量进行了测试,这些用户有和没有关注者,并且它有效。