我有一个文档术语矩阵,我想分成两个,一组用于训练,另一组用于测试。
我试过下面的代码:
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
实际结果如下:
> 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
我的预期结果是一个包含两个文档(#2和#4)的训练矩阵和一个包含三个文档(#1,#3和#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
任何人都可以帮助我理解为什么这不起作用?谢谢。
您可以简化代码,只需按dtm $ dimnames $ Documents中的位置信息进行子集化
希望这可以帮助:
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