无论如何,有没有阻止我的循环被速率限制打扰的方法?我希望我的代码等待执行,直到可能的时限过去。

附带问题:我考虑过并行化for循环。您认为这是个好主意吗?我不确定是否有机会将数据写入错误的文件。

library(rtweet)
create_token(app="Arconic Influential Followers",consumer_key,consumer_secret)

flw <- get_followers("arconic")
fds <- get_friends("arconic")
usrs <- lookup_users(c(flw$user_id, fds$user_id))

for(i in 1:length(usrs$user_id)){

    a<-tryCatch({get_timeline(usrs$user_id[i])},
                error=function(e){message(e)}
       )
    tryCatch({save_as_csv(a,usrs$user_id[i])},
                error=function(e){message(e)}
       )

}

最佳答案

我可以通过将get_timeline()函数包装在以下代码中来解决该问题。
在等待速率限制重置所需的时间后,函数get_timeline_unlimited递归调用自身。到目前为止,它对我来说没有任何问题。

 get_timeline_unlimited <- function(users, n){

  if (length(users) ==0){
    return(NULL)
  }

  rl <- rate_limit(query = "get_timeline")

  if (length(users) <= rl$remaining){
    print(glue("Getting data for {length(users)} users"))
    tweets <- get_timeline(users, n, check = FALSE)
  }else{

    if (rl$remaining > 0){
      users_first <- users[1:rl$remaining]
      users_rest <- users[-(1:rl$remaining)]
      print(glue("Getting data for {length(users_first)} users"))
      tweets_first <- get_timeline(users_first, n, check = FALSE)
      rl <- rate_limit(query = "get_timeline")
    }else{
      tweets_first <- NULL
      users_rest <- users
    }
    wait <- rl$reset + 0.1
    print(glue("Waiting for {round(wait,2)} minutes"))
    Sys.sleep(wait * 60)

    tweets_rest <- get_timeline_unlimited(users_rest, n)
    tweets <- bind_rows(tweets_first, tweets_rest)
  }
  return(tweets)
}

关于r - 使用rtweet get_timeline()避免速率限制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42025979/

10-12 20:58