I have asked by a few people lately to help walk them through using twitter API in R, and I’ve always just directed them to the blog post I wrote last year during the US presidential debates not knowing that Twitter had changed a few things. Having my interest peaked through a potential project at work I tried using some of my old code only to confronted with errors.
First of all, you now need to have a consumer key and secret from twitter themselves. After some research, I found it really easy to get one by going to twitter and creating a new applications. Don’t be discouraged, anyone can get one. Here is what the page looks like:
You now have to authenticate within R by inserting your consumer key and secret into this code:
It should spit out text and uri to get and input a pin, like:
To enable the connection, please direct your web browser to:
When complete, record the PIN given to you and provide it here:
You are now ready to use the searchTwitter() function. Since I work in real estate software, Kwelia, I wanted to do sentiment analysis for apartment hunting in manhattan, so I wrote out the following:
searchTwitter('apartment hunting', geocode='40.7361,-73.9901,5mi', n=5000, retryOnRateLimit=1)
where “apartment hunting” is what I am searching for, the geocode is a lat long with greater circle of five miles of where the tweets are sent from (union square, manhattan), n is the number of tweets i want, and retweet modifies n to the limit of tweets available if n is too high. In this case you, I got back 177 tweets.