我正在尝试进行正向选择,并且在使用字符串公式时遇到了困难:
> df <- data.frame(x0=c(1,2,3), x1=c(3,2,1), y=c(1,0,1))
> f0 <- lm("y ~ 1", data=df)
> f1 <- formula(lm("y ~ .", data=df))
> step(f0, direction="forward", scope=f1)
Start: AIC=-2.51
y ~ 1
Error in eval(predvars, data, env) :
invalid 'envir' argument of type 'closure'
我知道如果需要的话,我可以省略字符串公式部分:
> f0 <- lm(y ~ 1, data=df)
> f1 <- formula(lm(y ~ ., data=df))
> step(f0, direction="forward", scope=f1)
Start: AIC=-2.51
y ~ 1
Df Sum of Sq RSS AIC
<none> 0.66667 -2.51223
+ x0 1 0 0.66667 -0.51223
+ x1 1 0 0.66667 -0.51223
Call:
lm(formula = y ~ 1, data = df)
Coefficients:
(Intercept)
0.6667
但是我希望能够动态命名我的因变量而不必对其进行硬编码。
答案 0 :(得分:2)
您快到了。您只需要在字符串公式周围添加as.formula
函数,例如
df <- data.frame(x0=c(1,2,3), x1=c(3,2,1), y=c(1,0,1))
f0 <- lm(as.formula("y ~ 1"), data=df)
f1 <- formula(lm(as.formula("y ~ ."), data=df))
step(f0, direction="forward", scope=f1)
# make some string formulae objects
step0 <- "y ~ 1"
step1 <- "y ~ ."
# use as.formula
s0 <- lm(as.formula(step0), data=df)
s1 <- formula(lm(as.formula(step1), data=df))
step(s0, direction="forward", scope=s1)
答案 1 :(得分:0)
正如@ konrad-rudolph在评论中已经建议的那样,您可以使用bquote
在回归中动态地指定因变量的名称 :
dependentVariable <- as.name("y")
f0 <- lm(as.formula(bquote(.(dependentVariable) ~ 1)), data=df)
f1 <- formula(lm(bquote(.(dependentVariable) ~ .), data=df))
step(f0, direction="forward", scope=f1)
或者如果您不介意使用字符串,请使用接近@meenaparam答案的解决方案:
dependentVariable <- "y"
f0 <- lm(as.formula(paste0(dependentVariable," ~ 1")), data=df)
#f1 <- formula(lm(as.formula(paste0(dependentVariable," ~ .")), data=df)) #Does call lm
#f1 <- as.formula(paste0(" ~ ", paste(names(df)[!grepl(dependentVariable, names(df))], collapse="+"))) #Does not call lm
f1 <- reformulate(names(df)[!grepl(dependentVariable, names(df))]) #Or using reformulate which creates a formula from a character vector
step(f0, direction="forward", scope=f1)
错误来自:
a <- lm("y ~ 1", data=df)
b <- lm(as.formula("y ~ 1"), data=df)
environment(formula(a)) #<environment: 0x56252c8a5fe0>
environment(formula(b)) #<environment: R_GlobalEnv>
因此对您的步骤进行以下最小更改将起作用:
f0 <- lm(as.formula("y ~ 1"), data=df) #as.formula is added here
f1 <- formula(lm("y ~ .", data=df))
step(f0, direction="forward", scope=f1)