R rtweet:如果没有为给定的 Twitter 句柄返回结果,search_tweets 循环不会继续

R rtweet: search_tweets loop does not continue if no results returned for a given Twitter handle

我有一个 Twitter 句柄的数据框。当我使用 search_tweets 函数遍历句柄时,如果其中一个 Twitter 句柄没有 return 任何结果,循环将停止收集推文。

我想构建循环,如果没有结果 returned,它会忽略句柄并移动到下一个。

我的句柄数据框如下所示:

handles=data.frame(`Twitter Handle`=c("@_CHKD","@AIDHC","@BannerChildrens","@BaptistOnline"))

循环看起来像这样:

# Loop through the twitter handles & store the results as individual dataframes
for(handle in twitter_handles) {
  result <- search_tweets(handle, n = 3500 , include_rts = FALSE,retryonratelimit = TRUE)
  result$`Twitter Handle` <- handle
  result$Source <- "Search"

  df_name <- paste(tolower(substring(handle, 2)),"_search")

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

当我 运行 循环时,它在遇到 return 什么都没有的句柄后抛出以下错误:

Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column

我曾尝试在线搜索解决方案,但没有成功。 任何指示都会非常有帮助。

所以对我来说,当我 search_tweets 没有推文的句柄(即“@BannerChildrens”)时,我没有看到错误,而是 return 一个空的 data.frame长度为 0。通过添加 if 语句,您可以排除所有没有推文的句柄。以下代码 returns 三个数据帧(“@_CHKD”、“@AIDHC”、“@BaptistOnline”)在我的全局环境中,没有错误。

handles=data.frame(`Twitter Handle`=c("@_CHKD","@AIDHC","@BannerChildrens","@BaptistOnline"), stringsAsFactors = FALSE)


for(handle in handles$Twitter.Handle) {

  result <- search_tweets(handle, n = 3500 , include_rts = FALSE,retryonratelimit = TRUE)

  if(length(result) != 0){
    result$`Twitter Handle` <- handle
    result$Source <- "Search"

    df_name <- paste0(tolower(substring(handle, 2)),"_search")

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