制作PlainTextDocuments的矢量

时间:2013-04-29 19:12:02

标签: r tm

我有这个闭包,用于在传输和扩充元数据的同时将一个PlainTextDocument解析为几个子PlainTextDocument

segment_doc <- function(doc) {
    txt = paste0(doc, collapse=' ')
    au <- meta(doc, tag='Author');
    desc <- meta(doc, tag='description');
    ori <- meta(doc, tag='origin');
    locmeta <- attr(doc,'LocalMetaData');

    function(df){
        dfrows <- nrow(df);
        v<-rep(NA,dfrows);
        for(i in 1:dfrows) {
            a <- df[i,'after'];
            b <- df[i, 'before'];
            m <- df[i, 'meta'];

            sec <-PlainTextDocument(mkmeta(b, a, txt), author= au, description=desc, origin=ori, heading = m, localmetadata= locmeta) 
            #verified using debug that sec is a 'PlainTextDocument' with the expected text and metadata 
            v[i]=sec;

        }
        v #should be a vector of PlainTextDocuments, BUT it is vector of character vectors. WHY??

    }
}

我可以使用如下:

# mycorpus is a Corpus object containing PlainTextDocuments
# sections is a data.frame with 3 columns of type character named 'before', 'after' and 'meta' and 6 rows

sectioner <- segment_doc(mycorpus[[1]]); 
ptv <- sectioner(sections); #expect a vector of 6 PlainTextDocuments

class(ptv);
[1] "character" 
length(ptv);
[1] 6

问题

  • 当放置在向量中时,为什么secPlainTextDocument对象转换为字符向量?
  • 如何让sectioner返回Corpus个对象? (PlainTextDocument s的向量也可以。)

我已阅读tm上的文档。是的,全部。这不应该那么难。我应该使用不同的方法吗?

1 个答案:

答案 0 :(得分:2)

sectioner返回字符向量的原因是因为您将v初始化为无法携带复杂对象的原子向量。相反,放在向量中的对象被强制转换为公共原子数据类型(这里是一个字符)。您可以使用

将v初始化为列表
v <- vector( length = dfrows, mode= 'list' ).