Skip to content

Instantly share code, notes, and snippets.

@jmsktm
Last active November 26, 2022 20:56
Show Gist options
  • Select an option

  • Save jmsktm/f4acd900805c707631d24969c1b3f264 to your computer and use it in GitHub Desktop.

Select an option

Save jmsktm/f4acd900805c707631d24969c1b3f264 to your computer and use it in GitHub Desktop.
WordCloud in R
#install.packages("tm", repos="http://cran.rstudio.com/")
#install.packages("twitteR", repos="http://cran.rstudio.com/")
#install.packages("wordcloud", repos="http://cran.rstudio.com/")
library("tm")
library("twitteR")
library("wordcloud")
CONSUMER_KEY = '<CONSUMER_KEY>'
CONSUMER_SECRET = '<CONSUMER_SECRET>'
ACCESS_TOKEN_KEY = '<ACCESS_TOKEN_KEY>'
ACCESS_TOKEN_SECRET = '<ACCESS_TOKEN_SECRET>'
setup_twitter_oauth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
startDate <- '2016-06-12'
endDate <- '2016-06-14'
count <- 1000
args <- commandArgs(trailingOnly = TRUE)
searchText <- args[1]
# Regex to remove URL and other non-symbols
cleanupRegex <- '(http[s]?://[A-Za-z0-9/.-]+)|([^A-Za-z])'
stopwords <- c("i", "he", "she", "it", "they", "is", "are", "and",
"that", "was", "were", "his", "her", "you", "him", "the", "but",
"has", "have", "had", "our", "this", "can", "our", "will", "can", "for", "your")
getText <- function (t) {
text <- t$getText()
text <- gsub(cleanupRegex, " ", text)
}
fn <- function(searchText) {
tweets <- searchTwitter(searchText, since=startDate, until=endDate, n=count, lang='en')
sapply(tweets, getText)
}
tweets <- c(fn(searchText))
print(tweets)
words <- Corpus(VectorSource(tweets))
words <- tm_map(words, removeWords, stopwords)
matrix <- as.matrix(TermDocumentMatrix(words))
v <- sort(rowSums(matrix), decreasing=TRUE)
d <- data.frame(word = names(v),freq=v)
wordcloud(words=d$word, freq=d$freq, min.freq=3, max.words=200, random.order=FALSE, rot.per=0.35, colors=brewer.pal(12, "Paired"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment