我有以下x
和y
:
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
包。有什么想法吗?
答案 0 :(得分:4)
您可以做到这一点,而无需增加负担,无需加载额外的程序包,也无需依赖它们,就可以使用base :: Vectorize以单线方式进行更改:
> alls = Vectorize(smooth.spline,"nknots",SIMPLIFY=FALSE)(x=x,y=y,nknots=myknots)
这将返回一个列表,其中每个元素是smooth.spline
的每个值的myknots
输出:
> 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
将依赖关系降至最低是一种好习惯。
答案 1 :(得分:3)
对于purrr
,我们使用map
library(purrr)
map(myknots, ~ myfoo(x, y, nknots = .x))