Skip to content

Instantly share code, notes, and snippets.

@glesica
Created February 24, 2013 23:30
Show Gist options
  • Save glesica/5026233 to your computer and use it in GitHub Desktop.
Save glesica/5026233 to your computer and use it in GitHub Desktop.
A really simple sentiment analysis function implemented in R that illustrates some of the nifty features of the R language.
sentiment <- function(str, words, weights=NULL) {
if (is.null(weights)) {
weights <- rep(1, length(words))
}
if (length(words) != length(weights)) {
stop('Length of words and weights not equal')
}
str.wts <- rep(0, length(str))
for (i in 1:length(words)) {
cts <- str_count(str, words[[i]])
str.wts <- str.wts + (cts * weights[[i]])
}
str.wts
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment