r - 多个数据帧的插入符训练功能作为功能

标签 r function r-caret caret

6 年前就有一个类似的问题,但一直没有解决 ( R -- Can I apply the train function in caret to a list of data frames? ) 这就是我再次提出这个话题的原因。

我目前正在为我的大型 R 项目编写自己的函数,我想知道是否有机会总结 pakage 的模型训练函数 train() >caret 用于具有不同预测变量的不同数据帧。 我的函数应如下所示:

lda_ex <- function(data, predictor){
   model <- train(predictor ~., data,
      method = "lda",
      trControl = trainControl(method = "none"),
      preProc = c("center","scale"))
   return(model)
}

之后使用它应该像这样工作:

data_iris <- iris
predictor_iris <- "Species"

iris_res <- lda_ex(data = data_iris, predictor = predictor_iris)

不幸的是,据我所知,R 公式无法处理作为输入的变量。

有什么我想念的吗? 预先感谢您帮助我!

解决这个问题对我保持功能表清洁和安全工作有很大帮助。

最佳答案

predictor_iris <- "Species" , 你基本上是在 predictor_iris 中保存一个字符串对象.因此,当你运行 lda_ex ,我猜你会遇到一些关于 formula 的错误train() 中的对象,因为您正在尝试使用协变量向量来预测字符串。

确实,我尝试了以下玩具示例:

X = rnorm(1000)
Y = runif(1000)

predictor = "Y"

lm(predictor ~ X)

这给出了有关变量长度差异的错误。

让我修改你的函数:

lda_ex <- function(data, formula){
  model <- train(formula, data,
                 method = "lda",
                 trControl = trainControl(method = "none"),
                 preProc = c("center","scale"))
  return(model)
}

关键区别在于现在我们必须传入整个 formula ,而不仅仅是预测变量。这样,我们就避免了与字符串相关的问题。

library(caret) # Recall to specify the packages needed to reproduce your examples!

data_iris <- iris
formula_iris = Species ~ . # Key difference!
iris_res <- lda_ex(data = data_iris, formula = formula_iris)

关于r - 多个数据帧的插入符训练功能作为功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70709618/

相关文章:

C - 自定义 qsort 不工作

javascript - instance.method 不是函数 (javascript)

r - 在使用公式用插入符号的 train() 训练的 randomForest 对象上使用 predict() 时出错

r - Eloquent 地更改 R 中的许多栅格单元值

r - 列出数据集中存在的列的值以及另一列的所有值

无法从函数返回 boolean 值

R - 从插入符号和 glmnet 套索模型对象中提取因子预测变量名称

r - 插入符train()预测的结果与预测值非常不同。

python - 为什么在 Python 中获取 postgreSQL 表比在 R 中慢得多?

r - 设置 runjags 图的选项