首页 > 解决方案 > 获取包含特征的文档百分比 - quanteda

问题描述

我试图了解有多少文档包含使用quanteda. 我知道它dfm_weight()是可用的,但我相信“道具”功能着眼于文档中的特征频率,而不是跨文档。

我的目标是避免必须做ifelse声明并将其全部保留在 中quanteda,但我不确定这是否可能。我正在寻找的输出是按年份分组的并排条形图,它具有沿 y 轴的特征和沿 x 的文档中出现的百分比。此处的解释将是“在 2018 年的所有评论中,有 20% 的人提到了 X 一词,而 2019 年这一比例为 24%。”

library(quanteda)
library(reshape2)
library(dplyr)

df$rownum = 1:nrow(df) # unique ID
dfCorp19 = df %>%
  corpus(df, text_field = 'WhatPromptedYourSearch', docid_field = 'rownum')

x = dfm(dfCorp19,
        remove=c(stopwords(), toRemove),
        remove_numbers = TRUE,
        remove_punct = TRUE) %>%
    textstat_frequency(groups ='year') 

x = x %>% group_by(group) %>% mutate(prop = ifelse(group=='2019', docfreq/802, docfreq/930))
x = dcast(x,feature ~ group, value.var='prop')

标签: rnlpquanteda

解决方案


这是使用一些演示数据的尝试,其中组是十年。

library("quanteda")
#> Package version: 1.5.1

docvars(data_corpus_inaugural, "decade") <-
    floor(docvars(data_corpus_inaugural, "Year") / 10) * 10

dfmat <- dfm(corpus_subset(data_corpus_inaugural, decade >= 1970))

target_word <- "nuclear"

现在我们可以为目标特征提取一个data.frame。请注意该rowSums()函数,否则,dfm 的任何切片仍然是 dfm(不是向量)。

df <- data.frame(docname = docnames(dfmat),
                 decade = docvars(dfmat, c("decade")),
                 contains_target = rowSums(dfmat[, "nuclear"]) > 0,
                 row.names = NULL)
df
#>         docname decade contains_target
#> 1    1973-Nixon   1970            TRUE
#> 2   1977-Carter   1970            TRUE
#> 3   1981-Reagan   1980           FALSE
#> 4   1985-Reagan   1980            TRUE
#> 5     1989-Bush   1980           FALSE
#> 6  1993-Clinton   1990           FALSE
#> 7  1997-Clinton   1990            TRUE
#> 8     2001-Bush   2000           FALSE
#> 9     2005-Bush   2000           FALSE
#> 10   2009-Obama   2000            TRUE
#> 11   2013-Obama   2010           FALSE
#> 12   2017-Trump   2010           FALSE

有了这个,总结比例并使用一些dplyrggplot2绘制它们是一件简单的事情。

library("dplyr")
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df2 <- df %>%
    group_by(decade) %>%
    summarise(n = n()) %>%
    mutate(freq = n / sum(n))

library("ggplot2")
g <- ggplot(df2, aes(y = freq, x = decade)) +
    geom_bar(stat = "identity") +
    coord_flip() +
    xlab("") + ylab("Proportion of documents containing target word")
g

reprex 包(v0.3.0)于 2019-10-21 创建


推荐阅读