title | output |
---|---|
App to Map Tutorial Part 1 |
html_notebook |
In order to do a one-time collection of tweets, you will need to access Twitter's REST API. The name of the R package that you have to download and load in order to access the REST API is the TwitteR package created by Jeff Gentry. You will also have to create a Twitter app in order to access the REST API. If you haven't already made one, go to apps.twitter.com and create an app. You will need the Consumer Key (API Key), Consumer Secret (API Secret), Access Token, and Access Token Secret.
1. To do a one-time collection of tweets based on user-defined search terms. 2. To save the tweets in a .csv file.
1. Open up R Studio and go to File > New File > R Script.
2. Install and load the twitteR package.
install.packages("twitteR")
library(twitteR)
3. Next, you will need to enter your API key, API secret, token, and token secret.
api_key <- '' #in the quotes, put your API key
api_secret <- '' #in the quotes, put your API secret
token <- '' #in the quotes, put your token
token_secret <- '' #in the quotes, put your token secret
4. You will need to connect to Twitter to access the REST API.
setup_twitter_oauth(api_key, api_secret, token, token_secret)
5. Time to do a Twitter search! Let's do a Twitter search of tweets about national parks:
tweets <- searchTwitter('@YellowstoneNPS OR #YellowstoneNationalPark OR Yellowstone National Park OR
@GrandCanyonNPS OR #GrandCanyon OR Grand Canyon OR @ShenandoahNPS OR ShenandoahNationalPark
OR Shenandoah National Park', n = 200, lang = 'en')
This code is simply saying to search for tweets which contain the hashtags, twitter handles, and names of these national parks. <font color = "blue", face = "Courier">(n = 200)in English<font color = "blue", face = "Courier">(lang = “en”).
8. After you have done your Twitter search, you want to save your results in a data frame.
tweets.df <-twListToDF(tweets)
9. Your search results can be transferred from a data frame to a csv format so you can view in Excel.
write.csv(tweets.df, 'C:\Users\YourName\Documents\ApptoMap\tweets.csv') #example file extension. Add your own!
10. Click "Run" .