Take the 2-minute tour ×

In the toy example below, I converted the variable name cyl to 1_cyl. I am doing this as in my actual data there are some variables that starts with a number. I am applying randomForest using that formula but I am getting the error shown below. I see that another functions work perfect with the same formula.

How can I sove this problem?

colnames(mtcars)[2] = '1_cyl'
#[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)
share|improve this question
I don't see a convincing reason why a variable name must start with a number. The file reading functions do a good job of sanitizing names and not doing that is just asking for trouble. –  Roland Jul 25 '13 at 14:16
Your options are (1) don't use the formula interface for randomForest, or (2) don't name your variables like that. Since your variable names violate R's syntax for names, there's no reason to expect any function to honor them (even if some others will). –  joran Jul 25 '13 at 14:17
add comment

1 Answer

randomForest.formula has a call inside it to reformulate, for some reason, and it looks like that function doesn't like nonstandard names. (It's also calling model.frame twice.)

You can get around this by calling randomForest without a formula, but with a model matrix and response variable. When you use a formula this is what happens anyway; randomForest.formula is just a convenience wrapper that builds the model matrix for you.

randomForest(mtcars[, -1], mtcars[, 1])
share|improve this answer
add comment

Your Answer


