gpt4 book ai didi

r - 在向量上映射一个函数

转载 作者:行者123 更新时间:2023-12-02 14:57:27 25 4
gpt4 key购买 nike

我有以下 xy:

set.seed(1234)
x <- seq(1, 1000, 1)
y <- rnorm(1000)

我需要使用 smooth.spline 为它们建模:

model <- smooth.spline(x, y, nknots = 10)

问题是我每次都需要修改nknots 来适应这个模型。表示节点的向量如下:

myknots <- seq(5, 15, 1)

我想创建自己的函数,例如:

myfoo <- function(x, y, nknots){
smooth.spline(x, y, nknots = nknots)
}

但我找不到直接的方法。我宁愿使用 purrr 包。有什么想法吗?

最佳答案

您可以做到这一点,而无需加载额外包的额外负担,并依赖它们在单行代码中使用 base::Vectorize 永远不会改变:

> alls = Vectorize(smooth.spline,"nknots",SIMPLIFY=FALSE)(x=x,y=y,nknots=myknots)

这将返回一个列表,其中每个元素都是 myknots 的每个值的 smooth.spline 输出:

> alls[[1]]
Call:
(function (x, y = NULL, w = NULL, df, spar = NULL, lambda = NULL,
cv = FALSE, all.knots = FALSE, nknots = .nknots.smspl, keep.data = TRUE,
...

Smoothing Parameter spar= 0.1318881 lambda= 0.01540768 (14 iterations)
Equivalent Degrees of Freedom (Df): 5.244268
Penalized Criterion (RSS): 984.4824
GCV: 0.99489
> alls[[2]]
Call:
(function (x, y = NULL, w = NULL, df, spar = NULL, lambda = NULL,
cv = FALSE, all.knots = FALSE, nknots = .nknots.smspl, keep.data = TRUE,
...

Smoothing Parameter spar= 0.2285265 lambda= 0.03658625 (12 iterations)
Equivalent Degrees of Freedom (Df): 5.006371
Penalized Criterion (RSS): 984.8108
GCV: 0.994746

将依赖关系保持在最低限度是一种很好的做法。

关于r - 在向量上映射一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52280803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com