I recently got asked to help someone figure out how to make a TwitterMap in R; the code stopped working after Twitter changed their API, requiring users to get authentication. A TwitterMap allows you to see geographically where other users are located that are following an account, and also where the others users are located that that user follows.
So how to get Twitter authentication? I believe you need to create a Twitter App. Here’s how.
Go to Twitter Apps and create new application – need to name it and give it a website for it, but it must be unique (to all developers, not just you). Now, that you’re in when you get the app made and go under my applications. Check out https://dev.twitter.com/apps/new if you can’t find it. You will be looking for the consumer key and consumer secret (risque?) that you need for authentication.
Below, (harvested from http://davetang.org/muse/2013/04/06/using-the-r_twitter-package/) needs to be run. This authenticates your Twitter account/application and allows you to go back to scraping away the day. Replace YOULLGETTHISFROMTWITTER with the consumer key and secret in the code then run.
require("ROAuth") require("twitteR") # necessary step for Windows download.file(url = "http://curl.haxx.se/ca/cacert.pem", destfile = "cacert.pem") # to get your consumerKey and consumerSecret see the twitteR documentation # for instructions cred <- OAuthFactory$new(consumerKey = "YOULLGETTHISFROMTWITTER", consumerSecret = "YOULLGETTHISFROMTWITTER", requestURL = "https://api.twitter.com/oauth/request_token", accessURL = "http://api.twitter.com/oauth/access_token", authURL = "http://api.twitter.com/oauth/authorize") # necessary step for Windows cred$handshake(cainfo = "cacert.pem")
During this spot, you need to authenticate the key by going to a website and then entering it into
R. Think of this as an
ask=TRUE scenario, where if you ran a bunch of code after it, the authentication fails, so only run up to this point.
# save for later use save(cred, file = "~/twitter_authentication.Rdata")
Now, we’ll just save it into a data file for later use. Now, don’t re-run the code above, just save the credentials so you don’t have to do again.
##  TRUE
Now with all that secret handshaking done, Twitter knows who you are and you can get to business. Let’s make a TwitterMap:
and see the results!
twitterMap("strictlystat", userLocation = "Baltimore", plotType = "both")
## Getting data from Twitter, this may take a moment. ## Getting geographic (latitude/longitude) of Twitter users. ## Plotting results.
Thanks to @acfrazee for pointing out that this half-thrown together post looked like shit (but in a much nicer way). I appreciate the feedback!