Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's my solution using <code>try</code> to a similar problem with the Twitter API. </p> <p>I was asking the Twitter API for the number of followers for each person in a long list of Twitter users. When a user has their account protected I would get an error and the loop would break before I put in the <code>try</code> function. Using <code>try</code> allowed the loop to keep working by skipping onto the next person on the list.</p> <p>Here's the setup</p> <pre><code># load library library(twitteR) # # Search Twitter for your term s &lt;- searchTwitter('#rstats', n=1500) # convert search results to a data frame df &lt;- do.call("rbind", lapply(s, as.data.frame)) # extract the usernames users &lt;- unique(df$screenName) users &lt;- sapply(users, as.character) # make a data frame for the loop to work with users.df &lt;- data.frame(users = users, followers = "", stringsAsFactors = FALSE) </code></pre> <p>And here's the loop with <code>try</code> to handle errors while populating users$followers with follower counts obtained from Twitter API</p> <pre><code>for (i in 1:nrow(users.df)) { # tell the loop to skip a user if their account is protected # or some other error occurs result &lt;- try(getUser(users.df$users[i])$followersCount, silent = TRUE); if(class(result) == "try-error") next; # get the number of followers for each user users.df$followers[i] &lt;- getUser(users.df$users[i])$followersCount # tell the loop to pause for 60 s between iterations to # avoid exceeding the Twitter API request limit print('Sleeping for 60 seconds...') Sys.sleep(60); } # # Now inspect users.df to see the follower data </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload