如何解决如何评估具有不同参数的函数而不必继续用 R 写出来
ls <- score_model_compound(data,pred,tmp$Prediction,score= "log")
bs <- score_model_compound(data,score="Brier")
ss <- score_model_compound(data,score="spherical")
我想要的是这样的
ls = data.frame()
ls <- score_model_compound(data,score= c("log","Brier","spherical"))
是否有我可以使用的函数,例如 apply()
,可以让我执行此操作?
谢谢
解决方法
您可以创建某种包装函数,只将第一个参数作为您想要改变的参数,然后将其传递给 lapply
:
## Creating the wrapping function
my.wrapping.function <- function(score,data,pred,tmp) {
return(score_model_compound(data = data,pred = pred,tmp = tmp,score = score))
}
## Making the list of variables
my_variables <- as.list(c("log","Brier","spherical"))
## Running the function for all the variables (with the set specific arguments)
result_list <- lapply(my_variables,my.wrapping.function,data = data,pred = pred,tmp = tmp$Prediction)
最后,要将其转换为 data.frame(或矩阵),您可以对结果使用 do.call(cbind,...)
函数:
## Combining the results into a table
my_results_table <- do.call(cbind,result_list)
这是否回答了您的问题?
,mapply()
来救援:
score_v = c('spherical','log','Brier')
l = mapply(
score_model_compound,# function
score = score_v,# variable argument vector
MoreArgs = list(data = data,# fixed arguments
pred = pred),SIMPLIFY = FALSE # don't simplify
)
您可能需要自己稍微调整一下,因为您没有提供可重现的示例。 mapply(SIMPLIFY = FALSE)
将输出一个列表。如果函数返回 data.frame 的结果列表 data.frame 随后可以绑定到例如data.table::rbindlidst()
。
或者,您也可以使用循环:
l = list()
for (i in seq_along(score_v)) {
sc = score_v[i]
message('Modeling: ',sc)
smc = score_model_compound(data,score = sc)
l[[i]] = smc
names(l)[i] = sc
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。