这是我对x和y的所有可能组合进行逐步回归的代码。
library(tidyverse)
ys <- names(mtcars)
xs <- map(ys, ~setdiff(names(mtcars), .x)) %>%
map(~paste0(.x, collapse = "+")) %>%
unlist()
models <- tibble(ys, xs) %>%
mutate(startformula = paste0(ys, " ~ ", 1),
endformula = paste0(ys, " ~ ", xs)) %>%
mutate(model = map2(startformula, endformula, ~possibly(glm(.x, data=mtcars, family=gaussian, maxit = 100) %>% step(direction = "forward", scope = .y, trace = FALSE), otherwise = NA))) %>%
mutate(pred = map(model, augment))
当我可能不使用时,出现错误:
Evaluation error: No augment method for objects of class logical.
为避免这种情况,当我尽可能使用时,出现错误:
Evaluation error: Can't convert a `glm` object to function
我在这里想念什么?
答案 0 :(得分:0)
使用library(broom)
library(tidyverse)
library(broom)
ys <- names(mtcars)
xs <- map(ys, ~setdiff(names(mtcars), .x)) %>%
map(~paste0(.x, collapse = "+")) %>%
unlist()
models <- tibble(ys, xs) %>%
mutate(startformula = paste0(ys, " ~ ", 1),
endformula = paste0(ys, " ~ ", xs)) %>%
mutate(model = map2(startformula,
endformula,
~glm(.x, data=mtcars, family=gaussian, maxit = 100) %>%
step(direction = "forward", scope = .y, trace = FALSE), otherwise = NA)) %>%
mutate(pred = map(model, augment))
> models
A tibble: 11 x 6
ys xs startformula endformula model pred
<chr> <chr> <chr> <chr> <list> <list>
1 mpg cyl+disp+hp+drat+wt+qsec+vs+am+gear+carb mpg ~ 1 mpg ~ cyl+disp+hp+drat+wt+qsec+vs+am+gear+carb <S3: glm> <data.frame [32 x 12]>
2 cyl mpg+disp+hp+drat+wt+qsec+vs+am+gear+carb cyl ~ 1 cyl ~ mpg+disp+hp+drat+wt+qsec+vs+am+gear+carb <S3: glm> <data.frame [32 x 17]>
3 disp mpg+cyl+hp+drat+wt+qsec+vs+am+gear+carb disp ~ 1 disp ~ mpg+cyl+hp+drat+wt+qsec+vs+am+gear+carb <S3: glm> <data.frame [32 x 14]>
4 hp mpg+cyl+disp+drat+wt+qsec+vs+am+gear+carb hp ~ 1 hp ~ mpg+cyl+disp+drat+wt+qsec+vs+am+gear+carb <S3: glm> <data.frame [32 x 13]>
...
> sessionInfo()
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.1 LTS
Matrix products: default
BLAS: /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 LC_MONETARY=en_US.UTF-8
[6] LC_MESSAGES=en_US.UTF-8 LC_PAPER=en_US.UTF-8 LC_NAME=C LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] broom_0.4.2 bindrcpp_0.2 forcats_0.2.0 stringr_1.2.0 dplyr_0.7.4 purrr_0.2.4 readr_1.1.1 tidyr_0.7.2
[9] tibble_1.3.4 ggplot2_2.2.1 tidyverse_1.2.1