Code: Retrieving tweets via Twitter API in R

twitter3

Already in my previous posts we discussed the use of streamR package. Here we are gonna discover how to retrieve tweets from twitter API.

## Part 2: Fetching tweets from twitter via twitter API in R

## Author : Solomon AathiRaj, @Solomon1195

## Once you've successfully established your connection, you don't need to repeat it again.

library(httr)
library(devtools)
library(twitteR)

setup_twitter_oauth(consumer_key = apiKey, consumer_secret = apiSecret,
access_token = accessToken, access_secret = accessSecret)

## Type 1: Fetching tweets, converting it to data frames but not storing to your local disk

# basic searches by keywords

tweets <- searchTwitter("#CelebratingJio", n=20)

# converting tweets to data frame
tweets <- twListToDF(tweets)

# NOTE: limited to most recent ~3000 tweets
tweets <- searchTwitter("#RelianceJio", n=500)

# new tweets will be appended
tweets <- twListToDF(tweets)
tweets$created

# Type 2: Lets you store your retrieved tweets (in .json format) to your local disk

library("streamR")

# Refer streamR pdf from CRAN site to learn how to work with its functions

# filterStream of streamR has 9 arguments
filterStream(file.name = "#2Point0.json", track = c("#2Point0","#Endhiran2"), language = "en",
tweets = "50", oauth = my.oauth, verbose = "TRUE")

# parsetweets() of streamR opens tweets in .json file as data frames in R
2Point0 <- parseTweets("#2Point0_tweets.json")


Leave a comment