Stephen Clark
Stephen Clark

Reputation: 596

How to subset a document term matrix for training

I have a document term matrix that I'd like to divide into two, one set for training and the other for testing.

I have tried the code below:

library(tm)

text.vector <- c("The quick brown dog",
"jumped over",
"the lazy fox",
"How now brown cow",
"The cow jumped over the moon")

text.corpus <- VCorpus(VectorSource(text.vector))
text.dtm <- DocumentTermMatrix(text.corpus)

set.seed(123)
train.vector <- sample(5,2,replace=F)
train.vector

train.boolean <- text.dtm$i %in% train.vector
train.boolean

text_train.dtm <- text.dtm[train.boolean,]
text_test.dtm <- text.dtm[!train.boolean,]

table(text.dtm$i)
table(text_train.dtm$i)
table(text_test.dtm$i)

text.dtm
text_train.dtm
text_test.dtm

The actual results are:

> table(text.dtm$i)

1 2 3 4 5 
4 2 3 4 5 
> table(text_train.dtm$i)

1 
5 
> table(text_test.dtm$i)

1 2 3 4 
4 2 3 4 

My expected results are a training matrix with two documents (#2 and #4) and a testing matrix of three documents (#1, #3 and #5):

> table(text.dtm$i)

1 2 3 4 5 
4 2 3 4 5 
> table(text_train.dtm$i)

2 4 
2 4
> table(text_test.dtm$i)

1 3 5 
4 3 5 

Can anyone help me understand why this isn't working? Thanks.

Upvotes: 1

Views: 783

Answers (1)

Dimitri Graf
Dimitri Graf

Reputation: 141

You can simplify your code and just subset by the position information in dtm$dimnames$Documents

Hope this helps:

set.seed(123)
train.vector <- sample(5,2,replace=F)
train.vector

text_train.dtm <- text.dtm[text.dtm$dimnames$Docs %in% train.vector,]
text_test.dtm <- text.dtm[!(text.dtm$dimnames$Docs %in% train.vector),]

table(text.dtm$i)
1 2 3 4 5 
4 2 3 4 5 

table(text_train.dtm$i)
1 2 
2 4

table(text_test.dtm$i)
1 2 3 
4 3 5 

Upvotes: 1

Related Questions