我有一个代码,如果我使用 LM,则可以工作,但如果我使用 GAM,则不行。我猜想无论出于什么原因,LM 都会在对象内部查找变量,而 GAM 只会查看对象的名称,但我没有任何线索。
library(modelr)
library(purrr)
library(mgcv)
dataf <- data(cars)
dataf <- mtcars
df_split <- crossv_mc(dataf,10)
# LM - works
fn_model <- function(df){
lm(mpg ~ wt, data = df)
}
df_split_model <-
df_split %>%
mutate(model = map(train, fn_model)) %>%
print()
# GAM - does not
fn_model <- function(df){
mgcv::gam(mpg ~ wt, data = df)
}
df_split_model <-
df_split %>%
mutate(model = map(train, fn_model)) %>%
print()
#But i can do
gam(mpg~wt,data=mtcars)
您需要将传递给
resample
的 fn_model
对象显式转换为数据框。对于可以传递给 gam
参数的对象,lm
似乎比 data
更具体一些。
fn_model <- function(df){
mgcv::gam(mpg ~ wt, data = as.data.frame(df))
}
df_split_model <-
df_split %>%
mutate(model = map(train, fn_model)) %>%
print()
#> # A tibble: 10 x 4
#> train test .id model
#> <list> <list> <chr> <list>
#> 1 <resample [25 x 11]> <resample [7 x 11]> 01 <gam>
#> 2 <resample [25 x 11]> <resample [7 x 11]> 02 <gam>
#> 3 <resample [25 x 11]> <resample [7 x 11]> 03 <gam>
#> 4 <resample [25 x 11]> <resample [7 x 11]> 04 <gam>
#> 5 <resample [25 x 11]> <resample [7 x 11]> 05 <gam>
#> 6 <resample [25 x 11]> <resample [7 x 11]> 06 <gam>
#> 7 <resample [25 x 11]> <resample [7 x 11]> 07 <gam>
#> 8 <resample [25 x 11]> <resample [7 x 11]> 08 <gam>
#> 9 <resample [25 x 11]> <resample [7 x 11]> 09 <gam>
#> 10 <resample [25 x 11]> <resample [7 x 11]> 10 <gam>