【问题标题】:how to remove empty documents from document term matrix in R如何从R中的文档术语矩阵中删除空文档
【发布时间】:2018-05-16 06:04:28
【问题描述】:

我正在对推特数据执行 kmeans 聚类,为此我正在清理推文并创建一个语料库。后来我找到了dtm并使用了tf-idf理论。

但是我的 dtm 中几乎没有我想删除的空文档,因为 kmeans 无法为空文档运行。

这是我的代码:

removeURL <- function(x) gsub("http[[:alnum:][:punct:]]*", "", x) 
replacePunctuation <- function(x)
{
  x <- tolower(x)
  x <- gsub("[.]+[ ]"," ",x)
  x <- gsub("[:]+[ ]"," ",x)
  x <- gsub("[?]"," ",x)
  x <- gsub("[!]"," ",x)
  x <- gsub("[;]"," ",x)
  x <- gsub("[,]"," ",x)
  x <- gsub("[@]"," ",x)
  x <- gsub("[???]"," ",x)
  x <- gsub("[€]"," ",x)
  x

}

myStopwords <- c(stopwords('english'), "rt")


#preprocessing
tweet_corpus <- Corpus(VectorSource(tweet_raw$text))
tweet_corpus_clean <- tweet_corpus %>%
  tm_map(content_transformer(tolower)) %>% 
  tm_map(removeNumbers) %>%
  tm_map(removeWords,myStopwords) %>%
  tm_map(content_transformer(replacePunctuation)) %>%
  tm_map(stripWhitespace)%>%
  tm_map(content_transformer(removeURL))


dtm <- DocumentTermMatrix(tweet_corpus_clean ) 

#tf-idf

mat4 <- weightTfIdf(dtm) #when i run this, i get 2 docs that are empty
mat4 <- as.matrix(mat4)  

【问题讨论】:

  • 你能发一个 tweet_raw$text 的样本吗?
  • dtm 不是已经为空了吗?

标签: r cluster-analysis k-means corpus


【解决方案1】:

显然你不能对另一个 tm_map 这样做。

但是文本挖掘包也有tm_filter,可以用来过滤空文档。

【讨论】:

    【解决方案2】:

    如果您的文档不包含任何条目/单词,那么您可以这样做:

    rowSumDoc <- apply(dtm, 1, sum) 
    dtm2 <- dtm[rowSumDoc > 0, ] 
    

    基本上,上面我们首先对每个文档中的单词求和。稍后,我们会根据之前每个文档中单词的总和,对非空文档进行子集 dtm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 2015-05-05
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 2018-04-29
      • 2018-05-04
      相关资源
      最近更新 更多