0

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

我想构造循环,如果没有返回结果,它会忽略句柄并移至下一个。

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

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)
  }
}

当我运行循环时,它遇到一个不返回任何内容的句柄后会引发以下错误:

fix.by(by.x, x) 中的错误:“by”必须指定唯一有效的列

我试图在网上搜索解决方案,但没有成功。任何指针都会非常有帮助。

4

1 回答 1

1

search_tweets所以对我来说,当我处理没有推文的句柄(即“@BannerChildrens”)时,我没有看到错误,而是返回一个长度为 0 的空 data.frame。通过添加 if 语句,您可以排除所有没有推文的句柄推文。以下代码返回我的全局环境中没有错误的三个数据帧(“@_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)
    }
  }
}
于 2018-06-07T19:31:13.820 回答