调用存储在列表中的函数参数

Call a function argument stored in a list

我需要测试一组参数条件以找到最佳模型(使用 drc 包)。也就是说,我想将函数参数存储在一个列表中,然后将它们调用到 drm() 函数中。 drc 包有一个函数 (mselect()) 可以执行此操作,但已知它会因未知原因而失败 (https://www.reddit.com/r/Rlanguage/comments/a1bu44/any_idea_what_im_doing_wrong_with_the_mselect/)。


示例数据

library(drc) # This also loads in the S.alba data
data(S.alba)

head(S.alba)
  Dose  Herbicide DryMatter
1    0 Glyphosate       4.7
2    0 Glyphosate       4.6
3    0 Glyphosate       4.1
4    0 Glyphosate       4.4
5    0 Glyphosate       3.2
6    0 Glyphosate       3.0

尝试失败

# List of function arguments to be assessed e.g. drm(...fct = W1.4(fixed = c(NA, 0.1, NA, NA)
model_list <- list(curve = c(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))

# Failed function, attempting to return a list of results
model_select <- function(data, mlist){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = mlist)
    metric = AIC(model)
    return(metric)
}
model_select(data = S.alba, mlist = model_list)

Error in drm(DryMatter ~ Dose, Herbicide, data = ., fct = mlist) : First entry in list to 'fct' NOT a function

半成品尝试

model_select_2 <- function(data){
    model =  data %>%
        drm(DryMatter ~ Dose, Herbicide, data = . , fct = W1.4(fixed = c(NA, 0.1, NA, NA)))
    metric = AIC(model)
    return(metric)
}
model_select_2(data = S.alba)

model_select_2(data = S.alba)
[1] 106.9226

期望输出

model_select(data = S.alba, mlist = model_list)
[1] W1.4-106.9226
[2] LL.4-99.54702

部分问题在于您的创建方式 model_list。您希望将这些值与 list() 而不是 c() 组合。后者试图将它们组合成同一个对象。

接下来您可以做的是 sapply 遍历曲线列表以获得每个输入的结果。一个可行的例子是

model_list <- list(curve = list(W1.4(fixed = c(NA, 0.1, NA, NA)),
                             LL.4(fixed = c(NA, 0.1, NA, NA))))
model_select <- function(data, mlist){
   sapply(mlist$curve, function(curve){
      model <- drm(DryMatter ~ Dose, Herbicide, data = data , fct = curve)
      metric = AIC(model)
   })
}
model_select(data = S.alba, mlist = model_list)
# [1] 106.92259  99.54702