2014-11-14 76 views
2

有时,当将具有分类列的数据帧拆分为测试和训练集时,训练集将不包含分类变量的所有级别。当你再训练模型,并试图预测测试集,预测将失败:如何在测试和训练集中拆分数据帧时保留所有级别的分类变量R

例如:

x <- data.frame(...) # data frame with columns with very dispersed categorical variables 
set.seed(123) 
smp_size <- floor(0.75 * nrow(x)) 
train_idx <- sample(seq_len(nrow(x)), size = smp_size) 
train_set <- x[train_idx, ] 
test_set <- x[-train_idx, ] 
m <- lm(some_formula, data=train_set) 
predict(m, newdata=test_set) 

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : 
    factor xxxx has new levels yyy ... 

有谁知道一个方便的方法来设置所有分类变量的水平训练和测试都设置为原始数据集中的水平?

谢谢。

回答

0

插入符函数createDataPartition()会尝试处理您描述的问题。

鉴于你上面的例子,你应该能够使用这种方式:

train_idx <- createDataPartition(y, times = 1, p = 0.75, list=F)

这里是关于函数createDataPartition的R文件的一部分: “随机抽样内完成当y是试图平衡分裂内类别分布的因素时,y的水平。“

相关问题