Explore data

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
lyrics <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-12-14/lyrics.csv")
## Rows: 1885 Columns: 9
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (6): artist_name, album_name, song_name, section_name, line, section_artist
## dbl (3): track_number, song_id, line_number
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
lyrics %>% distinct(album_name)
## # A tibble: 3 × 1
##   album_name
##   <chr>     
## 1 Spice     
## 2 Spiceworld
## 3 Forever
lyrics %>% distinct(album_name, song_name)
## # A tibble: 31 × 2
##    album_name song_name                 
##    <chr>      <chr>                     
##  1 Spice      "Wannabe"                 
##  2 Spice      "Say You\x92ll Be There"  
##  3 Spice      "2 Become 1"              
##  4 Spice      "Love Thing"              
##  5 Spice      "Last Time Lover"         
##  6 Spice      "Mama"                    
##  7 Spice      "Who Do You Think You Are"
##  8 Spice      "Something Kinda Funny"   
##  9 Spice      "Naked"                   
## 10 Spice      "If U Can\x92t Dance"     
## # ℹ 21 more rows
library(tidytext)

tidy_lyrics <-
  lyrics %>%
  mutate(song_name = str_replace_all(song_name, "\x92", "'")) %>%
  unnest_tokens(word, line) %>%
  anti_join(get_stopwords())
## Joining with `by = join_by(word)`
tidy_lyrics %>%
  count(word, sort = TRUE)
## # A tibble: 979 × 2
##    word      n
##    <chr> <int>
##  1 get     153
##  2 love    137
##  3 know    124
##  4 time    106
##  5 wanna   102
##  6 never   101
##  7 oh       88
##  8 yeah     88
##  9 la       85
## 10 got      82
## # ℹ 969 more rows
tidy_lyrics %>%
  count(song_name, word, sort = TRUE)
## # A tibble: 2,206 × 3
##    song_name                       word           n
##    <chr>                           <chr>      <int>
##  1 Saturday Night Divas            get           91
##  2 Spice Up Your Life              la            64
##  3 If U Can't Dance                dance         60
##  4 Holler                          holler        48
##  5 Never Give Up on the Good Times never         47
##  6 Move Over                       generation    41
##  7 Saturday Night Divas            deeper        41
##  8 Move Over                       yeah          39
##  9 Something Kinda Funny           got           39
## 10 Never Give Up on the Good Times give          38
## # ℹ 2,196 more rows

Train a topic model

lyrics_sparse <-
  tidy_lyrics %>%
  count(song_name, word) %>%
  cast_sparse(song_name, word, n)

dim(lyrics_sparse)
## [1]  31 979
library(stm)
## stm v1.3.6.1 successfully loaded. See ?stm for help. 
##  Papers, resources, and other materials at structuraltopicmodel.com
set.seed(123)
topic_model <- stm(lyrics_sparse, K = 4, verbose = FALSE)
summary(topic_model)
## A topic model with 4 topics, 31 documents and a 979 word dictionary.
## Topic 1 Top Words:
##       Highest Prob: get, wanna, time, right, night, deeper, come 
##       FREX: deeper, saturday, comin, get, lover, fun, night 
##       Lift: another, blameless, breaking, clean, damsel, disgrace, fixed 
##       Score: deeper, saturday, get, wanna, lover, arms, comin 
## Topic 2 Top Words:
##       Highest Prob: dance, yeah, love, know, generation, next, baby 
##       FREX: next, naked, denying, foolin, nobody, wants, lead 
##       Lift: check, foolin, forevermore, nobody, trying, whatcha, chico 
##       Score: next, dance, naked, generation, colour, denying, foolin 
## Topic 3 Top Words:
##       Highest Prob: got, love, holler, make, oh, play, yeah 
##       FREX: holler, kinda, swing, funny, yay, trust, loving 
##       Lift: driving, guaranteed, 2000, anyone, anything, bottom, fantasy 
##       Score: holler, swing, kinda, funny, yay, ashamed, loving 
## Topic 4 Top Words:
##       Highest Prob: la, never, give, time, know, love, way 
##       FREX: times, swear, la, bring, promise, viva, tried 
##       Lift: able, certain, love's, rely, affection, shy, replace 
##       Score: la, times, aha, swear, chicas, front, havin

Explore topic model results

word_topics <- tidy(topic_model, matrix = "beta")
word_topics
## # A tibble: 3,916 × 3
##    topic term        beta
##    <int> <chr>      <dbl>
##  1     1 achieve 1.41e- 3
##  2     2 achieve 2.12e- 4
##  3     3 achieve 5.61e- 9
##  4     4 achieve 3.76e-15
##  5     1 baby    8.22e- 3
##  6     2 baby    1.83e- 2
##  7     3 baby    2.24e- 6
##  8     4 baby    4.32e- 3
##  9     1 back    1.87e- 2
## 10     2 back    5.99e- 4
## # ℹ 3,906 more rows
word_topics %>%
  group_by(topic) %>%
  slice_max(beta, n = 10) %>%
  ungroup() %>%
  mutate(topic = paste("Topic", topic)) %>%
  ggplot(aes(beta, reorder_within(term, beta, topic), fill = topic)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(vars(topic), scales = "free_y") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_reordered() +
  labs(x = expression(beta), y = NULL)

song_topics <- tidy(topic_model,
  matrix = "gamma",
  document_names = rownames(lyrics_sparse)
)
song_topics
## # A tibble: 124 × 3
##    document                   topic    gamma
##    <chr>                      <int>    <dbl>
##  1 2 Become 1                     1 0.370   
##  2 Denying                        1 0.00165 
##  3 Do It                          1 0.994   
##  4 Get Down With Me               1 0.479   
##  5 Goodbye                        1 0.000666
##  6 Holler                         1 0.00168 
##  7 If U Can't Dance               1 0.000879
##  8 If You Wanna Have Some Fun     1 0.954   
##  9 Last Time Lover                1 0.997   
## 10 Let Love Lead the Way          1 0.00149 
## # ℹ 114 more rows
song_topics %>%
  mutate(
    song_name = fct_reorder(document, gamma),
    topic = factor(topic)
  ) %>%
  ggplot(aes(gamma, topic, fill = topic)) +
  geom_col(show.legend = FALSE) +
  facet_wrap(vars(song_name), ncol = 4) +
  scale_x_continuous(expand = c(0, 0)) +
  labs(x = expression(gamma), y = "Topic")

effects <-
  estimateEffect(
    1:4 ~ album_name,
    topic_model,
    tidy_lyrics %>% distinct(song_name, album_name) %>% arrange(song_name)
  )
summary(effects)
## 
## Call:
## estimateEffect(formula = 1:4 ~ album_name, stmobj = topic_model, 
##     metadata = tidy_lyrics %>% distinct(song_name, album_name) %>% 
##         arrange(song_name))
## 
## 
## Topic 1:
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)
## (Intercept)           0.21970    0.13072   1.681    0.104
## album_nameSpice       0.04679    0.18936   0.247    0.807
## album_nameSpiceworld  0.07222    0.18657   0.387    0.702
## 
## 
## Topic 2:
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)
## (Intercept)            0.1574     0.1321   1.191    0.244
## album_nameSpice        0.1510     0.1912   0.789    0.436
## album_nameSpiceworld   0.1374     0.1857   0.740    0.466
## 
## 
## Topic 3:
## 
## Coefficients:
##                      Estimate Std. Error t value Pr(>|t|)  
## (Intercept)           0.23183    0.11143   2.081   0.0467 *
## album_nameSpice       0.08604    0.15806   0.544   0.5905  
## album_nameSpiceworld -0.21939    0.15581  -1.408   0.1701  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## 
## Topic 4:
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)   
## (Intercept)           0.391290   0.138792   2.819  0.00874 **
## album_nameSpice      -0.281995   0.196504  -1.435  0.16235   
## album_nameSpiceworld  0.007429   0.192449   0.039  0.96948   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
tidy(effects)
## # A tibble: 12 × 6
##    topic term                 estimate std.error statistic p.value
##    <int> <chr>                   <dbl>     <dbl>     <dbl>   <dbl>
##  1     1 (Intercept)           0.218       0.131    1.66   0.107  
##  2     1 album_nameSpice       0.0469      0.189    0.248  0.806  
##  3     1 album_nameSpiceworld  0.0729      0.189    0.387  0.702  
##  4     2 (Intercept)           0.158       0.132    1.20   0.241  
##  5     2 album_nameSpice       0.150       0.190    0.791  0.435  
##  6     2 album_nameSpiceworld  0.139       0.186    0.748  0.461  
##  7     3 (Intercept)           0.232       0.110    2.10   0.0445 
##  8     3 album_nameSpice       0.0834      0.156    0.533  0.598  
##  9     3 album_nameSpiceworld -0.221       0.154   -1.43   0.163  
## 10     4 (Intercept)           0.390       0.138    2.82   0.00871
## 11     4 album_nameSpice      -0.282       0.191   -1.48   0.151  
## 12     4 album_nameSpiceworld  0.00951     0.192    0.0496 0.961