我的 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
有谁能指导我如何实现所需的结果吗?
回答:
这里有一个使用 qdap
和 tm
的方法:
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