将参数作为 R 中的列表提供给函数

Feeding paramteres to a function as a list in R

我想比较不同的模型,为了节省时间,我考虑是否可以为函数中的单个参数输入值列表,并可能绘制结果。

我的具体示例 - 我对平滑样条感兴趣,所以模型是:

fit <- smooth.splines( x=train_x, y=train_y, df=seq(2, 20, by=0.5) )

这一切都很好,但是我如何 select 通过 "df" 进行不同的匹配?

丑陋但你可以做一个循环

fits_out <- list()
for(i in 1:50){
fits[[i]] <- smooth.splines( x=train_x, y=train_y, df=i )
}

然后您可以从列表对象中访问每个模型拟合

我不完全确定你想做什么,但如果你只想创建具有不同自由度的样条曲线,你需要对其进行迭代,smooth.spline 在其 [=13] 中未矢量化=]参数:

fits = lapply(seq(2, 20, by = 0.5), smooth.spline, x = train_x, y = train_y, w = NULL)

这样调用,lapply 会改变 df 参数;你也可以写得更明确:

fits = lapply(
    seq(2, 20, by = 0.5),
    function (df) smooth.spline(x = train_x, y = train_y, df = df)
)