代码之家  ›  专栏  ›  技术社区  ›  Varun

r rtweet:如果给定的twitter句柄没有返回结果,则search\u tweets循环不会继续

  •  0
  • Varun  · 技术社区  · 8 年前

    我有一个twitter句柄的数据框。当我使用 search_tweets 函数,如果其中一个twitter句柄不返回任何结果,则循环停止收集tweets。

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

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

    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”必须指定唯一有效的列

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

    1 回复  |  直到 8 年前
        1
  •  1
  •   D.sen    8 年前

    所以对我来说,当我 search_tweets 对于没有tweets的句柄(即“@bannerchildrens”),我返回一个长度为0的空data.frame。通过添加if语句,可以排除所有没有tweets的句柄。下面的代码返回我的全局环境中的三个数据帧(“@uchkd”、“@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)
        }
      }
    }
    
    推荐文章