使用rpart库时出现以下错误
dt <- rpart(formula, method="class", data=full.df.allAttr.train);
Error in model.frame.default(formula = formula, data = full.df.allAttr.train, :
object is not a matrix
当我将full.df.allAttr.train转换为矩阵
时dt <- rpart(formula, method="class", data= as.matrix( full.df.allAttr.train));
Error in model.frame.default(formula = formula, data = as.matrix(full.df.allAttr.train), :
'data' must be a data.frame, not a matrix or an array
当我检查类类型时,它是一个数据框
class(full.df.allAttr.train)
[1] "data.frame"
感谢您输入,当我使用具有结果的正确列名创建公式时,错误消失了。
measurevar <- "SpeakerName"
formula_str <- paste(measurevar, paste(rowNames, collapse=" + "), sep=" ~ ")
formula <- as.formula(formula_str)
它给出了不同的错误,因为我的数据框有row.names,因为下面的文本是快照
Error in model.frame.default(formula = formula, data = full.df.train, :
variable lengths differ (found for 'character(0)')
对不起,我将添加完整的源代码和数据集
library(tm)
library(rpart)
obamaCorpus <- Corpus(DirSource(directory = "D:/R/Chap 6/Speeches/obama" , encoding="UTF-8"))
romneyCorpus <- Corpus(DirSource(directory = "D:/R/Chap 6/Speeches/romney" , encoding="UTF-8"))
fullCorpus <- c(obamaCorpus,romneyCorpus)#1-22 (obama), 23-44(romney)
fullCorpus.cleansed <- tm_map(fullCorpus, removePunctuation)
fullCorpus.cleansed <- tm_map(fullCorpus.cleansed, stripWhitespace)
fullCorpus.cleansed <- tm_map(fullCorpus.cleansed, tolower)
fullCorpus.cleansed <- tm_map(fullCorpus.cleansed, removeWords, stopwords("english"))
fullCorpus.cleansed <- tm_map(fullCorpus.cleansed, PlainTextDocument)
#fullCorpus.cleansed <- tm_map(fullCorpus.cleansed, stemDocument)
full.dtm <- DocumentTermMatrix(fullCorpus.cleansed)
full.dtm.spars <- removeSparseTerms(full.dtm , 0.6)
full.matix <- data.matrix(full.dtm.spars)
full.df <- as.data.frame(full.matix)
full.df[,"SpeakerName"] <- "obama"
full.df$SpeakerName[21:44] <- "romney"
train.idx <- sample(nrow(full.df) , ceiling(nrow(full.df)* 0.6))
test.idx <- (1:nrow(full.df))[-train.idx]
rowNames <- colnames(full.df)
measurevar <- "SpeakerName"
formula_str <- paste(measurevar, paste(rowNames, collapse=" + "), sep=" ~ ")
formula <- as.formula(formula_str)
dt <- rpart(formula, method="class", data=full.df.train);
最后一步失败
数据集在这里 https://drive.google.com/folderview?id=0B1SogodTE-kJSHF6aFRmQURsV0U&usp=sharing
答案 0 :(得分:0)
您忘记加入full.df.train
,但您的公式不合适。
这将有效:
full.df.train <- full.df[train.idx, ]
dt <- rpart(SpeakerName ~ ., method = "class", data = full.df.train)
您的公式存在的问题是,SpeakerName
的两边都包含~
。如果要使用所有变量,使用.
表达式将更加容易和紧凑。