Sentiment analysis

R/llm-sentiment.R

llm_sentiment

Description

Use a Large Language Model (LLM) to perform sentiment analysis from the provided text

Usage

 
llm_sentiment( 
  .data, 
  col, 
  options = c("positive", "negative", "neutral"), 
  pred_name = ".sentiment", 
  additional_prompt = "" 
) 
 
llm_vec_sentiment( 
  x, 
  options = c("positive", "negative", "neutral"), 
  additional_prompt = "", 
  preview = FALSE 
) 

Arguments

Arguments Description
.data A data.frame or tbl object that contains the text to be analyzed
col The name of the field to analyze, supports tidy-eval
options A vector with the options that the LLM should use to assign a sentiment to the text. Defaults to: ‘positive’, ‘negative’, ‘neutral’
pred_name A character vector with the name of the new column where the prediction will be placed
additional_prompt Inserts this text into the prompt sent to the LLM
x A vector that contains the text to be analyzed
preview It returns the R call that would have been used to run the prediction. It only returns the first record in x. Defaults to FALSE Applies to vector function only.

Value

llm_sentiment returns a data.frame or tbl object. llm_vec_sentiment returns a vector that is the same length as x.

Examples

 
library(mall) 
 
llm_use("ollama", "llama3.1", seed = 100, .silent = TRUE)  
 
reviews <- data.frame(review = c( 
  "This has been the best TV I've ever used. Great screen, and sound.", 
  "I regret buying this laptop. It is too slow and the keyboard is too noisy", 
  "Not sure how to feel about my new washing machine. Great color, but hard to figure" 
  )) 
 
llm_sentiment(reviews, review) 
#> # A tibble: 3 × 2
#>   review                                   .sentiment
#>   <chr>                                    <chr>     
#> 1 This has been the best TV I've ever use… positive  
#> 2 I regret buying this laptop. It is too … negative  
#> 3 Not sure how to feel about my new washi… neutral
 
# Pass custom sentiment options 
llm_sentiment(reviews, review, c("positive", "negative")) 
#> # A tibble: 3 × 2
#>   review                                   .sentiment
#>   <chr>                                    <chr>     
#> 1 This has been the best TV I've ever use… positive  
#> 2 I regret buying this laptop. It is too … negative  
#> 3 Not sure how to feel about my new washi… negative
 
# Specify values to return per sentiment  
llm_sentiment(reviews, review, c("positive" ~ 1, "negative" ~ 0)) 
#> # A tibble: 3 × 2
#>   review                                   .sentiment
#>   <chr>                                         <dbl>
#> 1 This has been the best TV I've ever use…          1
#> 2 I regret buying this laptop. It is too …          0
#> 3 Not sure how to feel about my new washi…          0
 
# For character vectors, instead of a data frame, use this function 
llm_vec_sentiment(c("I am happy", "I am sad")) 
#> [1] "positive" "negative"