在 tidyverse 工作流的 R 部分使用 step 函数,特别是使用 nest 和 map 函数

Using step function in R part of the tidyverse workflow, in particular, using the nest and map functions

我正在尝试拟合嵌套模型,我想在其上应用阶跃函数并为每个嵌套元素获取潜在预测变量的子集。

我目前 运行 遇到以下错误,特别是当 运行 阶跃函数时:

Error: Problem with mutate() input step_null_to_full. x cannot coerce class ‘"lm"’ to a data.frame i Input step_null_to_full is map2(...). i The error occurred in group 1: ID = 1.

这是生成的代码示例:

library(tidyverse)

data <- data.frame(ID = rep(1:10,30),
                   Year = rep(1981:2010,10),
                   x1 = rnorm(300,0,1),
                   x2 = rnorm(300,0,1),
                   x3 = rnorm(300,0,1),
                   x4 = rnorm(300,0,1),
                   x5 = rnorm(300,0,1),
                   x6 = rnorm(300,0,1),
                   Y =  rnorm(300,0,1))


model_pipe <- data %>% 
  group_by(ID) %>% 
  nest() %>% 
  mutate(mod_intercept = map(data,~ lm(Y ~ 1, data=.)),
         mod_full = map(data,~ lm(Y ~ ., data=.)),
         mod_full_int = map(data,~ lm(Y ~ .*., data=.)),
         step_null_to_full = map2(mod_intercept,mod_full, 
                                  ~ step(.x, scope = formula(.y), direction = 'forward',trace = 0)))

要完成这项工作,您需要在 step 函数中传递与您用于拟合模型同名的数据。在拟合模型时,我们使用了 data = .,因此将数据重命名为 . 并应用该函数。

library(tidyverse)

data %>% 
  group_by(ID) %>% 
  nest() %>% 
  mutate(mod_intercept = map(data,~ lm(Y ~ 1, data=.)),
         mod_full = map(data,~ lm(Y ~ ., data=.)),
         mod_full_int = map(data,~ lm(Y ~ .*., data=.)),
         step_null_to_full = pmap(list(mod_intercept,mod_full, data), 
                                  function(x, y, z) {
               `.` <- z
               step(x, scope = formula(y), direction = 'forward',trace = 0)
          })) -> result
result

#     ID data              mod_intercept mod_full mod_full_int step_null_to_full
#   <int> <list>            <list>        <list>   <list>       <list>           
# 1     1 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 2     2 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 3     3 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 4     4 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 5     5 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 6     6 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 7     7 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 8     8 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
# 9     9 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>             
#10    10 <tibble [30 × 8]> <lm>          <lm>     <lm>         <lm>