我可以组合 pairwise_cor 和 pairwise_count 以获得每对单词的 phi 系数和出现次数吗?

Can I combine pairwise_cor and pairwise_count to get the phi coefficient AND number of occurrences for each pair of words?

我是 R 的新手,我正在使用 widyr 进行文本挖掘。我成功地使用找到的方法 here 获得了文本每个部分中的共现词列表及其 phi 系数。

代码如下:

word_cors <- review_words %>%
  group_by(word) %>%
  pairwise_cor(word, title, sort = TRUE) %>%
  filter(correlation > .15)

我知道我还可以生成一个包含同时出现的词和它们出现的次数的数据框,使用如下代码:

word_pairs <- review_words %>%
  pairwise_count(word, title, sort = TRUE)

我需要的是一个table,它同时具有phi系数每对单词的出现次数。我一直在研究 pairwise_cor 和 pairwise_count 但仍然无法弄清楚如何将它们组合起来。如果我理解正确的话,连接只考虑一列进行匹配,所以我不能可靠地使用常规连接,因为在 item1 列中可能有多个对具有相同的词。

这可以使用 widyr 吗?如果没有,是否有另一个包可以让我这样做?

完整代码如下:

#Load packages
pacman::p_load(XML, dplyr, stringr, rvest, httr, xml2, tidytext, tidyverse, widyr)

#Load source material
prod_reviews_df <- read_csv("SOURCE SPREADSHEET.csv")

#Split into one word per row
review_words <- prod_reviews_df %>%
  unnest_tokens(word, comments, token = "words", format = "text", drop = FALSE) %>%
  anti_join(stop_words, by = c("word" = "word"))

#Find phi coefficient
word_cors <- review_words %>%
  group_by(word) %>%
  pairwise_cor(word, title, sort = TRUE) %>%
  filter(correlation > .15)

#Write data to CSV
write.csv(word_cors, "WORD CORRELATIONS.csv")

我想添加 pairwise_count,但我需要它和 phi 系数。

谢谢!

我今天发现并使用了merge,它似乎使用了两个相关列来合并数据。我不确定如何检查准确性,但我认为它有效。

如果您开始使用 tidy data principles 和 tidyverse 工具,我建议您一路走来 :) 并使用 dplyr 进行您感兴趣的连接。您可以使用 left_join 连接来自 pairwise_cor()pairwise_count() 的计算,如果你愿意,你可以从一个管道到另一个管道。

library(dplyr)
library(tidytext)
library(janeaustenr)
library(widyr)

austen_section_words <- austen_books() %>%
  filter(book == "Pride & Prejudice") %>%
  mutate(section = row_number() %/% 10) %>%
  filter(section > 0) %>%
  unnest_tokens(word, text) %>%
  filter(!word %in% stop_words$word)

austen_section_words %>%
  group_by(word) %>%
  filter(n() >= 20) %>%
  pairwise_cor(word, section, sort = TRUE) %>%
  left_join(austen_section_words %>%
              pairwise_count(word, section, sort = TRUE),
            by = c("item1", "item2"))

#> # A tibble: 154,842 x 4
#>        item1     item2 correlation     n
#>        <chr>     <chr>       <dbl> <dbl>
#>  1    bourgh        de   0.9508501    29
#>  2        de    bourgh   0.9508501    29
#>  3    pounds  thousand   0.7005808    17
#>  4  thousand    pounds   0.7005808    17
#>  5   william       sir   0.6644719    31
#>  6       sir   william   0.6644719    31
#>  7 catherine      lady   0.6633048    82
#>  8      lady catherine   0.6633048    82
#>  9   forster   colonel   0.6220950    27
#> 10   colonel   forster   0.6220950    27
#> # ... with 154,832 more rows