【问题标题】:First column of csv file as document number in calculating Document-Term matrix in Rcsv文件的第一列作为在R中计算Document-Term矩阵的文档编号
【发布时间】:2014-07-24 23:46:56
【问题描述】:

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

id,name
143,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    

谁能指导我如何达到预期的效果?

【问题讨论】:

  • 也许将 id 读取为行名?将rownames = 1 添加到 read.csv

标签: r csv matrix machine-learning tf-idf


【解决方案1】:

这是qdap + tm 的方法:

library(qdap)

dat <- read.transcript(text="id,name
143,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

【讨论】:

  • 在这里,它给出了一个额外的行id 和一个额外的列name,这会影响矩阵值的整个结果。所以,我需要删除我的headings 以忽略idname 出现在我的矩阵中并影响我的结果。
  • 很抱歉。错过了您提供的标题。查看我的编辑。
  • 你能给我解释一下这条线dat[, 2], dat[, 1],让我知道,我在做什么。
  • 这只是列索引。说 text.var 是第 2 列 (dat[, 2]),grouping.var 是第 1 列 (dat[, 1])。
  • 如果有 3 个列,dat 的值是多少(第一列是 id,第二列是 name,第三列是 address)?
猜你喜欢
  • 2014-08-05
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 2017-11-07
  • 2015-05-19
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
相关资源
最近更新 更多