在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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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