首页 > 解决方案 > stats::step 在函数中失败,因为在 lm 对象中找不到数据

问题描述

每个人!我尝试在自己的函数中使用 step 函数,但似乎 step 函数只检查全局变量而不检查函数中的变量。这是我的示例代码:

library(tidyverse)
# simple test function
my_step_function <- function(model_data, formula) {
  mod <- lm(formula, model_data, x = TRUE, y = TRUE)
  step_mod <- step(mod, direction = "both", trace = FALSE)
  summary(step_mod)
}
# test data
test <- tibble(
  x1 = 1:100,
  x2 = -49:50+9*rnorm(100),
  x3 = 50+5*rnorm(100),
  x4 = 10*rnorm(100),
  x5 = sqrt(1:100),
  y  = 5*x1 + 2*x2 + 10*x5 + rnorm(100)
) %>% nest(data = everything())
# can't work in map() function, this is where I first find the problem
test %>% 
  mutate(RW = map(
    data,
    ~ my_step_function(.x,formula = formula(y~.))
  ))
# error:can't find object 'model_data'

# can't work when used directly
my_step_function(test$data[[1]],formula = (y~.))
# error:can't find object 'model_data'

# still can't work when give a test variable name
test_data <- test$data[[1]]
my_step_function(test_data,formula = (y~.))
# error:can't find object 'model_data'

# work when the global variable name is same with the variable name in the function 
model_data <- test$data[[1]]
my_step_function(model_data,formula = (y~.))
# success!

如果有人能解决我的难题,我将不胜感激!谢谢大家!

标签: linear-regression

解决方案


推荐阅读