R – 在 Twitter 句柄列表上使用循环来提取推文并创建多个数据帧

R – Using a loop on a list of Twitter handles to extract tweets and create multiple data frames

我有一个 df,其中包含我希望定期抓取的 Twitter 句柄。

df=data.frame(twitter_handles=c("@katyperry","@justinbieber","@Cristiano","@BarackObama"))

我的方法论

我想要 运行 一个 for 循环,循环遍历我的 df 中的每个句柄并创建多个数据帧:

1) 通过使用 rtweet 库,我想使用 search_tweets 函数收集推文。

2) 然后我想将每个数据帧的新推文合并到现有推文中,然后使用 unique 函数删除任何重复的推文。

3) 对于每个数据框,我想添加一列,其中包含用于获取数据的 Twitter 句柄的名称。例如:对于使用句柄@BarackObama 获得的推文数据库,我想要一个名为 Source 的附加列,句柄为 @BarackObama。

4) 如果 API returns 0 条推文,我希望第 2) 步被忽略。很多时候,当 API returns 0 推文时,我会收到一个错误,因为它试图将一个空数据帧与现有数据帧合并。

5) 最后,我想将每次抓取的结果保存到不同的数据框对象中。每个数据框对象的名称将是其 Twitter 句柄,小写并且没有 @

我想要的输出

我想要的输出是 4 个数据帧,katyperryjustinbiebercristianobarackobama

我的尝试

library(rtweet)
library(ROAuth)

#Accessing Twitter API using my Twitter credentials

key <-"yKxxxxxxxxxxxxxxxxxxxxxxx"
secret <-"78EUxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
setup_twitter_oauth(key,secret)

#Dataframe of Twitter handles    
df=data.frame(twitter_handles=c("@katyperry","@justinbieber","@Cristiano","@BarackObama"))

# Setting up the query
query <- as.character(df$twitter_handles)
query <- unlist(strsplit(query,","))
tweets.dataframe = list()

# Loop through the twitter handles & store the results as individual dataframes
for(i in 1:length(query)){
  result<-search_tweets(query[i],n=10000,include_rts = FALSE)
  #Strip tweets that  contain RTs
  tweets.dataframe <- c(tweets.dataframe,result)
  tweets.dataframe <- unique(tweets.dataframe)
}

但是,如果给定句柄的 API returns 0 推文,我无法弄清楚如何在我的 for 循环中包含忽略连接步骤的部分。

此外,我的 for 循环在我的环境中没有 return 4 个数据帧,而是将结果存储为 Large list

我确定了一个 解决了一个与我面临的问题非常相似的问题,但我发现很难适应我的问题。

非常感谢您的意见。

编辑:我在“我的方法论”中添加了步骤 3),以防您也能提供帮助。

tweets.dataframe = list()

# Loop through the twitter handles & store the results as individual dataframes
for(i in 1:length(query)){
  result<-search_tweets(query[i],n=10,include_rts = FALSE)

  if (nrow(result) > 0) {  # only if result has data
    tweets.dataframe <- c(tweets.dataframe, list(result))
  }
}

# tweets.dataframe is now a list where each element is a date frame containing
# the results from an individual query; for example...

tweets.dataframe[[1]]

# to combine them into one data frame

do.call(rbind, tweets.dataframe)

回应回复...

twitter_handles <- c("@katyperry","@justinbieber","@Cristiano","@BarackObama")

# Loop through the twitter handles & store the results as individual dataframes
for(handle in twitter_handles) {
  result <- search_tweets(handle, n = 15 , include_rts = FALSE)
  result$Source <- handle

  df_name <- substring(handle, 2)

  if(exists(df_name)) {
    assign(df_name, unique(rbind(get(df_name), result)))
  } else {
    assign(df_name, result)
  }
}