4

我有一个 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 返回 0 条推文,我希望忽略步骤 2)。很多时候,当 API 返回 0 条推文时,我会在尝试将空数据框与现有数据框合并时收到错误消息。

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

我想要的输出

我想要的输出是 4 个数据帧,katyperry, justinbieber, cristiano& barackobama

我的尝试

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 返回给定句柄的 0 条推文,我无法弄清楚如何在我的 for 循环中包含忽略连接步骤的部分。

此外,我的 for 循环不会在我的环境中返回 4 个数据帧,而是将结果存储为Large list

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

您的意见将不胜感激。

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

4

1 回答 1

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)
  }
}
于 2018-04-24T09:21:40.060 回答