Explore data

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ 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
departures <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-04-27/departures.csv')
## Rows: 9423 Columns: 19
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr   (8): coname, exec_fullname, interim_coceo, still_there, notes, sources...
## dbl  (10): dismissal_dataset_id, gvkey, fyear, co_per_rol, departure_code, c...
## dttm  (1): leftofc
## 
## ℹ 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.

How many different company names?

departures %>% distinct(coname)
## # A tibble: 3,860 × 1
##    coname                      
##    <chr>                       
##  1 SONICBLUE INC               
##  2 AMERICAN AIRLINES GROUP INC 
##  3 ABBOTT LABORATORIES         
##  4 ADVANCED MICRO DEVICES      
##  5 AETNA INC                   
##  6 AHMANSON (H F) & CO         
##  7 AIR PRODUCTS & CHEMICALS INC
##  8 ALBERTO-CULVER CO           
##  9 ALBERTSON'S INC             
## 10 ALCAN INC                   
## # ℹ 3,850 more rows

How many different notes?

departures %>% distinct(notes)
## # A tibble: 7,756 × 1
##    notes                                                                        
##    <chr>                                                                        
##  1 "Ballard took over when the outgoing CEO said that the board has given itsel…
##  2 "Mr. Crandall, the chairman and chief executive, announced that he would ret…
##  3 "Donald Carty resigned as the head of American Airlines today, but an abrupt…
##  4 "The top two executives of Abbott Laboratories took Wall Street and the comp…
##  5 "Advanced Micro Devices founder and chairman Walter Sanders is to step down …
##  6 "Joseph T. Sebastianelli resigned as Aestna's president and chief executive …
##  7 "Richard H. Deihl has retired as chairman of H.F. Ahmanson & Co., the parent…
##  8 "In March, Ahmanson had agreed to be acquired. Within weeks, it would exist …
##  9 "DeKruif came up as an insurance salesman with H.F. Ahmanson & Co. and rose …
## 10 "Air Products and Chemicals (AP) said Thursday its board has elected AP pres…
## # ℹ 7,746 more rows

How many different CEOs have resigned from each company and who are they?

departures %>% distinct(coname, exec_fullname)
## # A tibble: 9,203 × 2
##    coname                       exec_fullname              
##    <chr>                        <chr>                      
##  1 SONICBLUE INC                L. Gregory Ballard         
##  2 AMERICAN AIRLINES GROUP INC  Robert L. Crandall         
##  3 AMERICAN AIRLINES GROUP INC  Donald J. Carty            
##  4 ABBOTT LABORATORIES          Duane L. Burnham           
##  5 ADVANCED MICRO DEVICES       Walter Jeremiah Sanders III
##  6 AETNA INC                    Ronald Edward Compton      
##  7 AHMANSON (H F) & CO          Richard H. Deihl           
##  8 AHMANSON (H F) & CO          Charles R. Rinehart        
##  9 AHMANSON (H F) & CO          Robert M. De Kruif         
## 10 AIR PRODUCTS & CHEMICALS INC Harold A. Wagner           
## # ℹ 9,193 more rows

Let’s start by tokenizing this text and removing a small set of stop words (as well as fixing that punctuation).

library(tidytext)

tidy_departures <-
  departures %>%
  mutate(notes = str_replace_all(notes, "\x92", "'")) %>%
  unnest_tokens(word, notes) %>%
  anti_join(get_stopwords())
## Joining with `by = join_by(word)`

What are the most common words in these notes after removing stop words?

tidy_departures %>%
  count(word, sort = TRUE)
## # A tibble: 25,553 × 2
##    word          n
##    <chr>     <int>
##  1 company    6713
##  2 executive  5447
##  3 chief      4946
##  4 chairman   4814
##  5 ceo        4744
##  6 board      4352
##  7 officer    4213
##  8 president  4042
##  9 mr         3845
## 10 inc        2945
## # ℹ 25,543 more rows

What are reoccurring words from the notes per company?

tidy_departures %>%
  count(coname, word, sort = TRUE)
## # A tibble: 225,242 × 3
##    coname                 word            n
##    <chr>                  <chr>       <int>
##  1 PHOTRONICS INC         macricostas    26
##  2 PHOTRONICS INC         mr             22
##  3 PHOTRONICS INC         company        21
##  4 CHECKFREE CORP         checkfree      20
##  5 MOTOROLA SOLUTIONS INC motorola       20
##  6 PDL BIOPHARMA INC      board          20
##  7 MAYORS JEWELERS INC/DE birks          18
##  8 PHOTRONICS INC         board          18
##  9 HSBC FINANCE CORP      household      17
## 10 HSBC FINANCE CORP      hsbc           17
## # ℹ 225,232 more rows

What is the count of each word?

tidy_departures %>%
  count(word, word, sort = TRUE)
## # A tibble: 25,553 × 2
##    word          n
##    <chr>     <int>
##  1 company    6713
##  2 executive  5447
##  3 chief      4946
##  4 chairman   4814
##  5 ceo        4744
##  6 board      4352
##  7 officer    4213
##  8 president  4042
##  9 mr         3845
## 10 inc        2945
## # ℹ 25,543 more rows

Train a topic model

To train a topic model with the stm package, we need to create a sparse matrix from our tidy dataframe of tokens.

departures_sparse <-
  tidy_departures %>%
  count(exec_fullname, word) %>%
  bind_tf_idf(word, exec_fullname, n) %>%
  slice_max(order_by = tf_idf, n = 1000) %>%
  cast_sparse(exec_fullname, word, n)

dim(departures_sparse)
## [1] 651 923
library(stm)
## Warning: package 'stm' was built under R version 4.3.2
## stm v1.3.6.1 successfully loaded. See ?stm for help. 
##  Papers, resources, and other materials at structuraltopicmodel.com
set.seed(123)
departures_model <- stm(departures_sparse, K = 3, verbose = FALSE)

To get a quick view of the results, we can use summary().

summary(departures_model)
## A topic model with 3 topics, 651 documents and a 923 word dictionary.
## Topic 1 Top Words:
##       Highest Prob: checkfree, tcby, barker, roadway, circus, justin, motorola 
##       FREX: checkfree, tcby, barker, roadway, circus, justin, motorola 
##       Lift: 75yrs, 49, checkfree, tcby, barker, roadway, circus 
##       Score: checkfree, tcby, barker, roadway, circus, justin, motorola 
## Topic 2 Top Words:
##       Highest Prob: regarding, gallagher, planned, web, exec, callon, dismissal 
##       FREX: planned, regarding, web, information, retirement, founder, advance 
##       Lift: planned, premeditated, bailey's, retirement, advance, orderly, sungard 
##       Score: planned, regarding, gallagher, web, exec, callon, dismissal 
## Topic 3 Top Words:
##       Highest Prob: execucomp, shaw, sold, heart, age, interim, appear 
##       FREX: shaw, heart, age, died, attack, goes, casey’s 
##       Lift: rusty, chip, goes, covering, accused, paased, away 
##       Score: execucomp, shaw, age, heart, interim, sold, died

Explore topic model results

To explore more deeply, we can tidy() the topic model results to get a dataframe that we can compute on. There are two possible outputs for this topic model, the “beta” matrix of topic-word probabilities and the “gamma” matrix of document-topic probabilities. Let’s start with the first.

departures_topics <- tidy(departures_model, matrix = "beta")
departures_topics
## # A tibble: 2,769 × 3
##    topic term             beta
##    <int> <chr>           <dbl>
##  1     1 info         2.59e- 9
##  2     2 info         1.43e- 3
##  3     3 info         5.51e- 7
##  4     1 fraud        7.76e- 9
##  5     2 fraud        2.87e- 3
##  6     3 fraud        2.25e- 6
##  7     1 75yrs        2.08e- 3
##  8     2 75yrs        2.38e-15
##  9     3 75yrs        1.25e-13
## 10     1 premeditated 1.52e-16
## # ℹ 2,759 more rows

Since this is a tidy dataframe, we can manipulate it how we like, include making a visualization showing the highest probability words from each topic.

departures_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)

departures_topics <- tidy(departures_model,
  matrix = "gamma",
  document_names = rownames(departures_sparse)
)
departures_topics
## # A tibble: 1,953 × 3
##    document                       topic  gamma
##    <chr>                          <int>  <dbl>
##  1 Larry Stephen Smith                1 0.0549
##  2 Anu D. Saad                        1 0.0549
##  3 Thomas G. Deranek                  1 0.784 
##  4 Wayne R. Weidner                   1 0.0393
##  5 C. Lee Cox                         1 0.0450
##  6 John R. Frantz                     1 0.0572
##  7 Clifford W. Illig                  1 0.0549
##  8 Russell A. Childs                  1 0.0572
##  9 Arif Shakeel                       1 0.0393
## 10 Christopher William Eccleshare     1 0.0393
## # ℹ 1,943 more rows
departures_topics %>%
    group_by(topic) %>%
    slice_max(order_by = gamma, n = 5) %>%
    ungroup() %>%
    
    mutate(
      notes = fct_reorder(document, gamma),
      topic = factor(topic)
    ) %>%
    ggplot(aes(gamma, topic, fill = topic)) +
    geom_col(show.legend = FALSE) +
    facet_wrap(vars(notes), ncol = 3) +
    scale_x_continuous(expand = c(0, 0)) +
    labs(x = expression(gamma), y = "Topic")

I tried to make this work but it wouldn’t

#{r} #effects <- # estimateEffect( # 1:3 ~ coname, # departures_model, # tidy_departures %>% distinct(word, coname) %>% arrange(word) # ) #

#Again, to get a quick view of the results, we can use summary(), but to dive deeper, we will want to use tidy().

#{r} #summary(effects) #

#{r} #tidy(effects) #

Questions

1.1 Our modeling goal is to “discover” topics in the notes of CEO Departures.

1.2 The dataset includes characteristics of a ceo departure: The name of the company (coname), executive name(exec_fullname) and the notes of the departure (notes).

1.3 The key variables used in the analysis are exec_fullname, and notes.

2.1 The dataset is transformed by tokenizing the text from the notes variable, removed stop words, and then the data is transformed into a sparse matrix.

3.1 The model used in the analysis is a Structural Topic Model (STM), a machine learning technique that is capable of discovering the hidden thematic structure within a large collection of documents.

3.2 The selection of the optimal value for ‘k’, the number of topics, is set to 3 as this dataset is small. However, the choice of ‘k’ is normally found by cross-validation or evaluating model fit.

4.1 The analysis revealed that three distinct topics can be found within the notes. The STM provided a list of words most associated with each topic.