Мы могли бы создать функции с помощью switch
для распознавания правильной модели, а затем использовать map
для циклического создания созданных столбцов
library(randomForest)
library(gbm)
library(purrr)
library(dplyr)
library(stringr)
-функций
country_model <- function(df, formula, model_name) {
switch(model_name,
"model1" = lm(formula = formula , data = df),
"model2" = randomForest(formula= formula, data = df),
"model3" = gbm(formula=formula, data = df, n.minobsinnode = 2)
)
}
country_pred <- function(model, model_name) {
switch(model_name,
"model1" = as.numeric(predict(model)),
"model2" = as.numeric(predict(model)),
"model3" = predict(model, n.trees = model[["n.trees"]])
)
}
Установитьимена списка формул с именами моделей
fmlst <- set_names(formula_list, str_c("model", seq_along(formula_list)))
Создайте столбцы модели отдельно с помощью imap
df1 <- imap_dfc(fmlst, ~ by_country %>%
transmute(!! .y := map(data,
country_model, formula = .x, model_name = .y ))) %>%
bind_cols(by_country, .)
str1 <- names(df1)[startsWith(names(df1), "model")]
str2 <- str_c("pred_", 1:3)
Создайте также столбцы прогноза
df2 <- map_dfc(str1, ~ {
nm1 <- .x
df1 %>%
select(.x) %>%
pull(1) %>%
map(., country_pred, model_name = nm1) %>%
list
}
) %>%
rename_all(~ str2) %>%
bind_cols(df1, .)
df2
# A tibble: 142 x 9
# country continent data model1 model2 model3 pred_1 pred_2 pred_3
# <fct> <fct> <list> <list> <list> <list> <list> <list> <list>
# 1 Afghanistan Asia <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 2 Albania Europe <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 3 Algeria Africa <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 4 Angola Africa <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 5 Argentina Americas <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 6 Australia Oceania <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 7 Austria Europe <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 8 Bahrain Asia <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# 9 Bangladesh Asia <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
#10 Belgium Europe <tibble [12 × 4]> <lm> <rndmFrs.> <gbm> <dbl [12]> <dbl [12]> <dbl [12]>
# … with 132 more rows