在R中计算文档-词矩阵时,将CSV文件的第一列作为文档编号

我的 data.csv 文件包含以下内容:

id,name143,The sky is blue.21,The sun is bright.23,The sun in the sky is bright.

现在,我可以这样读取整个文件:

> file_loc <- "test.csv"> x <- read.csv(file_loc, header = TRUE)> x <- data.frame(lapply(x, as.character), stringsAsFactors=FALSE)> require(tm)  Loading required package: tm> dd <- Corpus(DataframeSource(x))> dtm <- DocumentTermMatrix(dd, control = list(weighting = weightTfIdf))

我得到的结果矩阵是这样的:

> as.matrix(dtm)                Terms      Docs       143     blue.   bright.       sky       sun the      1 0.3962406 0.3962406 0.0000000 0.1462406 0.0000000   0      2 0.0000000 0.0000000 0.1949875 0.0000000 0.1949875   0      3 0.0000000 0.0000000 0.1169925 0.1169925 0.1169925   0

我希望将 csv 文件中的 id 列作为 docs 的名称,像这样:

                 Terms      Docs      blue.   bright.       sky       sun the      143 0.3962406 0.0000000 0.1462406 0.0000000   0      21 0.0000000 0.1949875 0.0000000 0.1949875   0      23 0.0000000 0.1169925 0.1169925 0.1169925   0    

有谁能指导我如何实现所需的结果吗?


回答:

这里有一个使用 qdaptm 的方法:

library(qdap)dat <- read.transcript(text="id,name143,The sky is blue.21,The sun is bright.23,The sun in the sky is bright.", sep=",", header=TRUE)## dat <- read.transcript("test.csv", sep=",")dd <- df2tm_corpus(dat[, 2], dat[, 1])library(tm)as.matrix(DocumentTermMatrix(dd, control = list(weighting = weightTfIdf)))##      Terms## Docs      blue.   bright.       sky       sun the##   143 0.5283208 0.0000000 0.1949875 0.0000000   0##   21  0.0000000 0.1949875 0.0000000 0.1949875   0##   23  0.0000000 0.1169925 0.1169925 0.1169925   0

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注