代码之家  ›  专栏  ›  技术社区  ›  Bhavya

从R中的dtm中按每个文档的频率提取顶部特征

  •  0
  • Bhavya  · 技术社区  · 8 年前

    我有一个dtm,希望从文档术语矩阵中按频率提取每个文档的前5个术语。

    我有一个 dtm 使用tm软件包构建

      Terms                     
    Docs aaaa aac abrt abused accept accepted
    1 0 0 0 0 0 0 
    2 0 0 0 0 0 0
    3 0 0 0 0 0 0
    4 0 0 0 0 0 0
    5 0 0 0 0 0 0
    6 0 0 0 0 0 0
    

    所需输出应为以下形式:

    Id   
    1   Term1 Term2 Term3 Term4 Term5
    2   Term1 Term2 Term3 Term4 Term5
    and so on for all the documents.
    

    我已经尝试了其他来源提供的所有解决方案 喜欢 Make dataframe of top N frequent terms for multiple corpora using tm package in R (转换为tdm,并试图将其转换为输出形式,但不起作用)和其他方法,但似乎不起作用。

    1 回复  |  直到 8 年前
        1
  •  1
  •   lukeA    8 年前

    使用Quanteda:

    library(quanteda)
    txt <- c("hello world world fizz", "foo bar bar buzz")
    dfm <- dfm(txt)
    topfeatures(dfm, n = 2, groups = seq_len(ndoc(dfm)))
    # $`1`
    # world hello 
    # 2     1 
    # 
    # $`2`
    # bar foo 
    # 2   1 
    

    您也可以在 DocumentTermMatrix dfm .

    或者使用经典 tm

    library(tm)
    packageVersion("tm")
    # [1] ‘0.7.1’
    txt <- c(doc1="hello world world", doc2="foo bar bar fizz buzz")
    dtm <- DocumentTermMatrix(Corpus(VectorSource(txt)))
    n <- 5
    (top <- findMostFreqTerms(dtm, n = n))
    # $doc1
    # world hello 
    # 2     1 
    # 
    # $doc2
    # bar buzz fizz  foo 
    # 2    1    1    1 
    do.call(rbind, lapply(top, function(x) { x <- names(x);length(x)<-n;x }))
    # [,1]    [,2]    [,3]   [,4]  [,5]
    # doc1 "world" "hello" NA     NA    NA  
    # doc2 "bar"   "buzz"  "fizz" "foo" NA 
    

    findMostFreqTerms 从开始提供 tm version 0.7-1 .