linear-regression - 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!
如果有人能解决我的难题,我将不胜感激!谢谢大家!
解决方案
推荐阅读
- regex - 如何使用正则表达式在 .* 之后直接用 $ 结束字符串?
- c# - GC.Collect() 的目的
- mysql - 一个数据库还是几个?
- node.js - 如何在 UnityEditor 中正确关闭 socket.io 连接?
- python - 将带有金融缩写的数字字符串转换为浮点数
- python-3.x - 使用 LinkExtractor 的 Scrapy 不从网站中提取链接
- jquery - 根据条件格式化选项文本
- ejb - 在会话 bean 和实体 bean 上定义资源引用标签
- ruby-on-rails - Rails - Passing a specific column to query by count of an associated model
- datetime - 必要时修复格式以包含前导零