我正在使用rpart做出决策树。例如:

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


如何从文本文件中读取公式部分,并以rpart喜欢的格式获取它?我试过了:

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


但我得到一个错误:

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


如何格式化rpart_formula,以便rpart正确看到它?

最佳答案

使用as.formula

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

08-20 00:09