在R中将模型公式作为参数传递

4
我需要在相同的数据上交叉验证多个glmer模型,因此我编写了一个函数来完成这个任务(我不想使用现有的函数来完成此任务)。我想将任意的glmer模型作为唯一参数传递给我的函数。不幸的是,我无法弄清楚如何做到这一点,而网络也没有给我答案。
理想情况下,我想做类似以下的事情:
model = glmer(y ~ x + (1|z), data = train_folds, family = "binomial"
model2 = glmer(y ~ x2 + (1|z), data = train_folds, family = "binomial"

然后调用cross_validation_function(model)cross_validation_function(model2)。函数内的训练数据称为train_fold。
但是,我怀疑我需要使用reformulate以不同的方式传递模型公式。
这是我的一个函数示例。该项目旨在从行为特征预测自闭症(ASD)。数据变量为da
library(pacman)
p_load(tidyverse, stringr, lmerTest, MuMIn, psych, corrgram, ModelMetrics, 
caret, boot)

cross_validation_function <- function(model){ 

  #creating folds  
  participants = unique(da$participant)
  folds <- createFolds(participants, 10)


  cross_val <- sapply(seq_along(folds), function(x) {

    train_folds = filter(da, !(as.numeric(participant) %in% folds[[x]]))
    predict_fold = filter(da, as.numeric(participant) %in% folds[[x]])

    #model to be tested should be passed as an argument here    
    train_model <-  model



    predict_fold <- predict_fold %>% 
      mutate(predictions_perc = predict(train_model, predict_fold, allow.new.levels = T),
             predictions_perc = inv.logit(predictions_perc),
             predictions = ifelse(predictions_perc > 0.5, "ASD","control"))

    conf_mat <- caret::confusionMatrix(data = predict_fold$predictions, reference = predict_fold$diagnosis, positive = "ASD") 

    accuracy <- conf_mat$overall[1]
    sensitivity <- conf_mat$byClass[1]
    specificity <- conf_mat$byClass[2]


    fixed_ef <- fixef(train_model) 

    output <- c(accuracy, sensitivity, specificity, fixed_ef)

    })

    cross_df <- t(cross_val)
    return(cross_df)
  }

从评论中开发的解决方案:使用as.formula可以将字符串转换为公式,然后可以按以下方式将其作为参数传递给我的函数:
cross_validation_function <- function(model_formula){
...
train_model <- glmer(model_formula, data = da, family = "binomial") 
...}

formula <- as.formula( "y~ x + (1|z"))
cross_validation_function(formula)
1个回答

1
如果你的目标是从已拟合的模型中提取模型公式,则可以使用attributes(model)$call[[2]]。然后,在使用cv folds拟合模型时,您可以使用此公式。
   mod_formula <-  attributes(model)$call[[2]]
   train_model = glmer(mod_formula , data = train_data, 
                family = "binomial")

我已经开发了一个解决方案,它不需要使用 as.formula 先适配模型。我已将其添加到原始帖子的底部。 - WiggyStardust
2
formula(model) 怎么样? - Ben Bolker
@WiggyStardust 就像我之前说的那样,我以为你想要从拟合模型中提取模型公式。像你现在这样传递公式确实更有意义。 - kangaroo_cliff

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接