R Caret替代列名称

时间:2019-01-08 16:53:24

标签: r r-caret substitution

我想用train包的caret函数内的列名代替。因此,我用target替换了目标变量eval(parse(text = paste0(targetname)))的列名。使用randomForest函数本身,我的代码可以正常工作。但是使用train会产生错误:

library(caret)
library(randomForest)
dat <- data.frame(target = c(2.5, 4.5, 6.1, 3.2, 2.2),
              A = c(1.3, 4.4, 5.5, 6.7, 8.1),
              B = c(44.5, 50.1, 23.7, 89.2, 10.5),
              C = c("A", "A", "B", "B", "B"))

targetname <- "target"

set.seed(42)
model <- train(eval(parse(text = paste0(targetname))) ~ A + B + C, 
                   data = dat, 
                   method="rf",
                   ntree = 250, 
                   metric= "RMSE")

此代码产生Error in [.data.frame(data, , all.vars(Terms), drop = FALSE) : undefined columns selected

我可以写什么代替替代targetname的表达式来代替eval(parse(text = paste0(targetname)))

1 个答案:

答案 0 :(得分:1)

您可以使用

formula(paste(targetname, " ~ A + B + C"))
# target ~ A + B + C

相同
model <- train(formula(paste(targetname, " ~ A + B + C")), 
               data = dat, 
               method="rf",
               ntree = 250, 
               metric= "RMSE")