【发布时间】:2018-09-21 14:28:53
【问题描述】:
我想创建一个从两个信息列表派生的值表,但我只想从第一个列表中获取满足第二个列表中定义的条件的元素。
我有两个列表作为 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”)。
我希望我可以自动删除我不想要的列。在我的真实表中,有数千列,我发现删除列的方法要求我为列命名。我不想为数千列这样做。理想情况下,我想要一种将 one_hot_table 作为输入的方法,在 DF_A 中查找每个列名,并生成一个新的数据框,其中只有前三个最常见的数据框。像这样的:
new_one_hot_table <- function(one_hot_table, DF_A, 3)
任何帮助将不胜感激。
【问题讨论】:
标签: r one-hot-encoding