我正在参与Kaggle泰坦尼克号比赛,关于缺失值填充我有一个问题。我的训练集包含因子和数字,我想使用Caret包中的preProcess
函数来填充缺失值,但在使用preProcess之前,我需要使用dummyVars
函数将所有的因子转换为虚拟变量。
dummies = dummyVars(survived ~ . -1, data = train, na.action = na.pass)
xtrain = predict(dummies, train)
然而,在使用
dummyVars
将因子转换的过程中,所有的NAs都被一些未知的算法预测出来,即使我已经指定了na.action = na.pass
,所有缺失的age
列都变成了1。我希望将我的因子转换为虚拟变量,但不要触及NAs,这样我就可以使用preProcess
函数来填充它们。我该怎么做呢?谢谢。
以下是需要翻译的内容:
dput here:
structure(list(survived = structure(c(1L, 2L, 2L, 2L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("0",
"1"), class = "factor"), pclass = structure(c(3L, 1L, 3L, 1L,
3L, 3L, 1L, 3L, 3L, 2L, 3L, 1L, 3L, 3L, 3L, 2L, 3L, 2L, 3L, 3L
), .Label = c("1", "2", "3"), class = "factor"), sex = structure(c(2L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L,
2L, 1L, 1L), .Label = c("female", "male"), class = "factor"),
age = c(22, 38, 26, 35, 35, NA, 54, 2, 27, 14, 4, 58, 20,
39, 14, 55, 2, NA, 31, NA), sibsp = c(1, 1, 0, 1, 0, 0, 0,
3, 0, 1, 1, 0, 0, 1, 0, 0, 4, 0, 1, 0), parch = c(0, 0, 0,
0, 0, 0, 0, 1, 2, 0, 1, 0, 0, 5, 0, 0, 1, 0, 0, 0), fare = c(7.25,
71.2833, 7.925, 53.1, 8.05, 8.4583, 51.8625, 21.075, 11.1333,
30.0708, 16.7, 26.55, 8.05, 31.275, 7.8542, 16, 29.125, 13,
18, 7.225), embarked = structure(c(4L, 2L, 4L, 4L, 4L, 3L,
4L, 4L, 4L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 3L, 4L, 4L, 2L), .Label = c("",
"C", "Q", "S"), class = "factor")), .Names = c("survived",
"pclass", "sex", "age", "sibsp", "parch", "fare", "embarked"), row.names = c(NA,
20L), class = "data.frame")
model.matrix
似乎也无法解决问题,因为它会省略任何带有 NA 的行。如果有办法让它起作用,请告诉我。谢谢。 - mchangun