如何避开R中的随机林错误(新数据中的预测值不匹配)

如何避开R中的随机林错误(新数据中的预测值不匹配),r,random-forest,R,Random Forest,我很难对下面的错误消息进行故障排除。我试图在titanic数据集上建立一个随机森林模型。有没有办法避免这个错误?是否有代码检查树中的级别 Error in predict.randomForest(my_rf_model, test1) : Type of predictors in new data do not match that of the training data. 这可能是因为test1中的一个预测变量是一个因子变量,其值在原始数据集中不存在。例如,如果titanic有

我很难对下面的错误消息进行故障排除。我试图在
titanic
数据集上建立一个随机森林模型。有没有办法避免这个错误?是否有代码检查树中的级别

Error in predict.randomForest(my_rf_model, test1) : Type of predictors in new data
    do not match that of the training data.

这可能是因为
test1
中的一个预测变量是一个因子变量,其值在原始数据集中不存在。例如,如果
titanic
有一个名为
group
的列,该列的值可以是
a
B
,但是
test1$group
的值可以是
C
,那么您将得到该错误

例如:

data(iris)
iris$group = factor(sample(c("A","B"), nrow(iris), replace=TRUE))
rf <- randomForest(Species ~ ., data=iris)

newdat = iris
newdat$group = "C"

predict(rf, newdata=newdat)
数据(iris)
iris$group=系数(样本(c(“A”、“B”)、nrow(iris)、replace=真)

rf或如果培训和测试集之间的级别不同。假设
titanic$组
的级别为“A”和“B”,但
test1$组
是仅为“A”级的因素。也就是说,除了额外的水平造成这一点,它也可能是失踪的水平。