r - 获取包含特征的文档百分比 - 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')
解决方案
这是使用一些演示数据的尝试,其中组是十年。
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
有了这个,总结比例并使用一些dplyr和ggplot2绘制它们是一件简单的事情。
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 创建
推荐阅读
- javascript - discord.js awaitmessage 不收集数据
- arrays - 如何在C中迭代char**?
- c - 将结构成员指针分配给另一个动态内存分配的指针是否安全?
- react-native - “UI-Kitten”选择组件不呈现值
- c - 与指针有关的警告
- vercel - Vercel 上的部署行为
- c# - 如何在 VS Code 中为 ASP.NET Core 设置默认端口?
- android - 新的 Google Play 控制台 - 首次应用发布的托管发布
- php - 如果用户登录 php,导航栏按钮排序
- typescript - 从打字稿到 postgres 的连接挂起