开发者

Reading rpart Input Parameters from a Text Variable

I'm using rpart to make a decision tree. For example:

fit <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis)

How do I read in the formula part from a text file and get it in a format that rpart likes? I've tried:

predictor_variables <- c("Age", "Number", "Start")
rpart_formula <- Kyphosis ~ parse(text=paste(predictor_variables, collapse="+"))
fit <- rpart(rpart_formula, data=kyphosis)

but I get a开发者_开发技巧n error:

 invalid type (expression) for variable 'parse(text = paste(predictor_variables, collapse = "+"))'

How can I format rpart_formula so that rpart sees it correctly?


Use as.formula:

rpart_formula <- as.formula(
    paste("Kyphosis ~ ", 
          paste(predictor_variables, collapse = " + "), 
          sep = ""
    )
)


Try simply passing the formula as a character string:

rpart_formula <-paste("Kyphosis ~ ",paste(predictor_variables, collapse="+"))

that should be coerced to a formula by rpart.

Edit

As noted in the comments below, not all functions will do the coercion for you, so you should not rely on this behavior, but in this case rpart most certainly does.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜