我想在 dfm 中操作(重命名和组合)功能,如何进行?
原因如下:我想使用与 Quanteda 中实现的 Porter 词干分析器(通过 Python 调用的 kpss 算法)不同的词干算法。
示例 三词句子 c("creatief creatieve creatie") 将生成具有三个特征(即“creatief”、“creatieve”、“creatie”)的 dfm,所有特征的词频均为 1。但是,kpss 算法将这些词的词干改为“creatie”。如果我可以将 dfm 中的这三个功能组合成一个名为“creatie”且术语频率为 3 的功能,那将会非常方便。
非常感谢您的帮助。
(注意。我知道在 dfm 转换为“简单”矩阵后可以进行此类数据操作,但我想在 dfm 中执行此操作)。
附录 我忽略了 dfm_compress 函数。我就快到了...压缩 dfm 后,是否也可以应用字典,例如单词“creati”和“innovati”都应该算作单词类别“creati”的出现次数(参见 dfm 中的字典功能)? (注意。鉴于文本量巨大,我宁愿不保留原始数据文件)
最佳答案
您可以通过创建 dfm,然后对特征进行词干分析,然后重新编译 dfm 以组合词干提取后相同的特征来实现此目的。
require(quanteda)
txt <- c("creatief creatieve creatie")
(dfm1 <- dfm(txt))
## Document-feature matrix of: 1 document, 3 features (0% sparse).
## 1 x 3 sparse Matrix of class "dfmSparse"
## features
## docs creatief creatieve creatie
## text1 1 1 1
这是我为您的示例近似的步骤,但您可以将下面的右侧字符串子集函数替换为您自己对特征字符向量的词干操作。
# this approximates what you can do with the Python-based stemmer
# note that here you must use colnames<- since there is no function
# featnames<- (for replacement)
colnames(dfm1) <- stringi::stri_sub(featnames(dfm1), 1, 7)
dfm1
## Document-feature matrix of: 1 document, 3 features (0% sparse).
## 1 x 3 sparse Matrix of class "dfmSparse"
## features
## docs creatie creatie creatie
## text1 1 1 1
然后您可以重新编译 dfm 来编译计数。
# this combines counts in featnames that are identical
dfm_compress(dfm1)
## Document-feature matrix of: 1 document, 1 feature (0% sparse).
## 1 x 1 sparse Matrix of class "dfmSparse"
## features
## docs creatie
## text1 3
请注意,如果您使用 quanteda 的词干分析器,此步骤可能是 dfm_wordstem()
:
dfm_wordstem(dfm1)
## Document-feature matrix of: 1 document, 1 feature (0% sparse).
## 1 x 1 sparse Matrix of class "dfmSparse"
## features
## docs creati
## text1 3
关于r - 操作(重命名和重新组合)dfm (quanteda) 中的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42963524/