r-如何处理randomForest包中以数字开头的变量名



在下面的玩具示例中,我将变量名cyl转换为1_cyl。我这样做是因为在我的实际数据中,有一些变量以数字开头。我正在使用该公式应用randomForest,但我得到了如下所示的错误。我发现,用同样的公式,另一个函数是完美的。

我怎样才能解决这个问题?

data(mtcars)
colnames(mtcars)[2] = '1_cyl'
colnames(mtcars)
#[1] "mpg"   "1_cyl" "disp"  "hp"    "drat"  "wt"    "qsec"  "vs"    "am"    "gear"  "carb" ]
(fmla <- as.formula(paste("mpg ~ `1_cyl`+hp ")) )
randomForest(fmla,  dat=mtcars,importance=T,na.action=na.exclude)
#> randomForest(fmla,  dat=mtcars,importance=T,na.action=na.exclude)
#Error in eval(expr, envir, enclos) : object '1_cyl' not found
#Another functions works!!!
rpart(fmla, dat=mtcars)
glm (fmla, dat=mtcars)
由于某种原因,

randomForest.formula内部有一个对reformulate的调用,而且该函数似乎不喜欢非标准名称。(它还调用了model.frame两次。)

您可以通过调用randomForest来绕过这一问题,不需要公式,而是使用模型矩阵和响应变量。当你使用一个公式时,无论如何都会发生这种情况;randomForest.formula只是一个为您构建模型矩阵的方便包装器。

randomForest(mtcars[, -1], mtcars[, 1])

最新更新