Skip to contents

This function calculates the average sentiment score for each book.

Usage

average_book_sentiment(sentiment_df)

Arguments

sentiment_df

A data frame containing the output from analyze_sentiment.

Value

A data frame with average sentiment scores for each book.

Examples

# \donttest{
# Create a temporary file with sample book IDs
temp_file <- tempfile(fileext = ".txt")
writeLines(c("1420", "2767052", "10210"), temp_file)

# Run the scrape_reviews function
reviews <- scrape_reviews(temp_file, num_reviews = 5, use_parallel = FALSE)
#> Total book IDs to process: 3
#> 2024-10-25 03:00:49.907424 scrape_goodreads_reviews: Completed! All book reviews extracted
#> Scraping run time = 7.80114316940308
#> Total books processed: 3

# Check if reviews were successfully scraped
if (nrow(reviews) > 0) {
  # Perform sentiment analysis
  sentiment_results <- analyze_sentiment(reviews, lexicon = "afinn")

  # Calculate average sentiment score per book
  avg_senti <- average_book_sentiment(sentiment_results)

  # Display the results
  print(avg_senti)
} else {
  cat("No reviews found. Cannot calculate average sentiment.\n")
}
#> # A tibble: 3 × 2
#>   book_id avg_sentiment
#>   <chr>           <dbl>
#> 1 10210            55.4
#> 2 1420            -72.7
#> 3 2767052          23.2

# Clean up: remove the temporary file
file.remove(temp_file)
#> [1] TRUE
# }