2013-02-11 30 views
1

我正在使用R tm软件包,试图将我的语料库拆分为训练集和测试集,并将其编码为用于选择的元数据。最简单的方法是什么(假设我试图将样本分成两半)?R tm语料库对象的拆分示例

这里有一些事情我已经试过:

  1. 我知道,当我键入...
> meta(d) 
    MetaID Y 
1  0 1 
2  0 1 

我看到ID,但似乎无法访问他们(为了说上半场属于一组,而第二组属于另一组)。 rownames(attributes(d)$DMetaData)给了我指数,但这看起来很丑,而且它们是因素。

  1. 现在,转换成数据帧后,说d是我的数据集,我只想说:
half <- floor(dim(d)[1]/2) 
d$train <- d[1:half,] 
d$test <- d[(half+1):(half*2),] 

但我怎么能轻易做这样的事情......

meta(d, tag="split") = ifelse((meta(d,"ID")<=floor(length(d)/2)),"train","test") 

...得到如下结果:

> meta(d) 
    MetaID Y split 
1  0 1 train 
2  0 1 train 
...  . . ... 
100  0 1 test 

不幸的是,meta(d,"ID")不起作用,但meta(d[[1]],"ID") == 1的做法,但是多余的。我正在寻找一种访问元ID的全矢量方法,或者一种通常更智能的子集分配方式,并将其分配给“split”元变量。

回答

4

一个语料库只是一个列表。所以你可以像普通列表一样分割它。这里举一个例子:

我创建了一些数据。我用数据tm

txt <- system.file("texts", "txt", package = "tm") 
(ovid <- Corpus(DirSource(txt))) 
A corpus with 5 text documents 

现在我拆我的数据,以训练和测试中

nn <- length(ovid) 
ff <- as.factor(c(rep('Train',ceiling(nn/2)), ## you create the split factor as you want 
       rep('Test',nn-ceiling(nn/2)))) ## you can add validation set for example... 
ll <- split(as.matrix(ovid),ff) 
ll 
$Test 
A corpus with 2 text documents 

$Train 
A corpus with 3 text documents 

然后我给你新的标签

ll <- sapply(names(ll), 
       function(x) { 
       meta(ll[[x]],tag = 'split') <- ff[ff==x] 
       ll[x] 
       }) 

您可以检查结果:

lapply(ll,meta) 
$Test.Test 
    MetaID split 
4  0 Test 
5  0 Test 

$Train.Train 
    MetaID split 
1  0 Train 
2  0 Train 
3  0 Train 
+0

+1虽然我会说这是一个列表不是矩阵。 – 2014-03-10 04:45:45

+0

@TylerRinker谢谢。我编辑我的答复反映你的评论。 – agstudy 2014-03-10 22:51:47

2
## use test corpus crude in tm 
library(tm) 
data(crude) 

#random training sample 
half<-floor(length(crude)/2) 
train<-sample(1:length(crude), half) 

# meta doesnt handle lists or vector very well, so loop: 
for (i in 1:length(crude)) meta(crude[[i]], tag="Tset") <- "test" 
for (i in 1:half) meta(crude[[train[i]]], tag="Tset") <- "train" 

# check result 
for (i in 1:10) print(meta(crude[[i]], tag="Tset")) 

这似乎工作。