从 R 中的频率计数列表创建一个热点 table

Creating a one hot table from a list of frequency counts in R

我想创建一个 table 来自两个信息列表的值,但我只想从第一个列表中获取满足第二个列表中定义的条件的元素。

我有两个列表作为 R 中的数据框。DF_A 是一个包含总频率计数的文档术语列表。 DF_B 是文档列表,其中包含文档中每个单词的频率。

这是我目前的 R 代码,它让我朝着我的目标迈进了一大步。

library(dplyr)
library(tidytext)

docs = read.csv("~/text.csv")
# > docs
# DOCID                                                      TEXT
# 1  Doc1       blue blue blue blue rose rose hats hats hats hats
# 2  Doc2                                               rose hats
# 3  Doc3  tall tall tall tall tall tall tall tall tall tall tall 
# 4  Doc4                                               cups cups
# 5  Doc5                                                    tall 

my_unigrams <- unnest_tokens(docs, unigram, TEXT, token = "ngrams", n = 1)

DF_A <- my_unigrams %>%
  count(unigram, sort = TRUE)

DF_A
#> DF_A
# A tibble: 5 x 2
# unigram     n
# <chr> <int>
# 1    tall    12
# 2    hats     5
# 3    blue     4
# 4    rose     3
# 5    cups     2

DF_B <- my_unigrams %>%
  count(DOCID, unigram, sort = TRUE)

# > DF_B
# A tibble: 8 x 3
# DOCID unigram     n
# <fctr>   <chr> <int>
# 1   Doc3    tall    11
# 2   Doc1    blue     4
# 3   Doc1    hats     4
# 4   Doc1    rose     2
# 5   Doc4    cups     2
# 6   Doc2    hats     1
# 7   Doc2    rose     1
# 8   Doc5    tall     1


# My goal is a "one hot" table where each document ID is a row name, and the top three most frequent terms are columns (each cell should contain either 1 or 0; basically yes/no that term occurs in that document). I want a table like this:

one_hot_table <- table(DF_B$DOCID,DF_B$unigram)
one_hot_table

# one_hot_table
#     blue  cups hats rose tall
# Doc1    1    0    1    1    0
# Doc2    0    0    1    1    0
# Doc3    0    0    0    0    1
# Doc4    0    1    0    0    0
# Doc5    0    0    0    0    1
上面的

"one_hot_table" 接近我想要的,除了我想要一个子集:只是最常见的单词 ("tall", "blue", "hats" ).

我希望我可以自动删除不需要的列。在我的真实 table 中,有数千列,我发现删除列的方法要求我为列命名。我不想为数千列这样做。理想情况下,我想要一种将 one_hot_table 作为输入的方法,在 DF_A 中查找每个列名,并生成一个新的数据框,其中只有前三个最频繁。像这样:

new_one_hot_table <- function(one_hot_table, DF_A, 3)

任何帮助将不胜感激。

好吧,如果您不介意将 DF_B 修改为新的数据表,一个简单的方法是:

DF_C <- DF_B %>% 
  semi_join(DF_A %>% 
              head(3), by = "unigram")

new_one_hot_table <- table(DF_C$DOCID,DF_C$unigram)

如果您仍然想要您的函数方法,我认为这应该可行(任意称为 hot_tablr):

hot_tablr <- function(one_hot_table, DF_A, select = 3){

  # First get a vector of column names of interest
  top <- DF_A %>% 
    head(select) %>% 
    pull(unigram)

  # Now only select columns of interest
  new <- one_hot_table[, top]

  return(new)

}

希望我没有正确理解你的问题。希望它是显而易见的,但我正在按照建议使用 dplyr 包。