textstat_polarity: Compute sentiment from key polarities

View source: R/textstat_polarity.R

textstat_polarityR Documentation

Compute sentiment from key polarities

Description

Compute sentiment scores using a polarity approach, based on assigned categories (types or features) of positive, negative, and neutral sentiment. Several formulas for combining the polar categories are available, or the user can supply a custom function.

Usage

textstat_polarity(x, dictionary, fun = sent_logit, ...)

Arguments

x

a character, corpus, tokens, or dfm object containing text, tokens, or features whose sentiment will be scored

dictionary

a dictionary that has polarity set, indicating which keys are associated with positive, negative, and (optionally) neutral sentiment

fun

function; the formula for computing sentiment, which must refer to pos, neg, and (optionally) neut. The default is the "logit" scale (Lowe et al 2011) which is the log of (positive / negative) counts. See sentiment-functions for details and for additional available functions, as well as details on how to supply custom functions.

...

additional arguments passed to fun

Value

a data.frame of sentiment scores

References

Lowe, W., Benoit, K. R., Mikhaylov, S., & Laver, M. (2011). Scaling Policy Preferences from Coded Political Texts. Legislative Studies Quarterly, 36(1), 123–155. \Sexpr[results=rd]{tools:::Rd_expr_doi("10.1111/j.1939-9162.2010.00006.x")}

Examples

library("quanteda")
corp <- tail(data_corpus_inaugural, n = 5)
toks <- tokens(corp)
dfmat <- dfm(toks)
polar1 <- list(pos = "positive", neg = "negative")
polar2 <- list(pos = c("positive", "neg_negative"),
               neg = c("negative", "neg_positive"))

polarity(data_dictionary_LSD2015) <- polar1
textstat_polarity(corp, dictionary = data_dictionary_LSD2015)
textstat_polarity(toks, dictionary = data_dictionary_LSD2015)
textstat_polarity(dfmat, dictionary = data_dictionary_LSD2015)

polarity(data_dictionary_LSD2015) <- polar2
textstat_polarity(corp, dictionary = data_dictionary_LSD2015)
textstat_polarity(toks, dictionary = data_dictionary_LSD2015)
textstat_polarity(corp, dictionary = data_dictionary_LSD2015)
textstat_polarity(dfmat, dictionary = data_dictionary_LSD2015)

# with a user-supplied function
sent_fn <- function(x) (x[, "pos"] - x[, "neg"]) / rowSums(x) * 100
textstat_polarity(toks, data_dictionary_LSD2015, fun = sent_fn)

quanteda/quanteda.sentiment documentation built on Feb. 26, 2024, 12:42 a.m.