将变量向量传递给lm()公式 [英] Pass a vector of variables into lm() formula
问题描述
我试图使我的代码片段自动化,以使编程变得不再那么乏味.
I was trying to automate a piece of my code so that programming become less tedious.
基本上,我试图使用 rms 包中的fastbw()
逐步选择变量.我想将fastbw()
选择的变量列表传递为y ~ x1+x2+x3
的公式,"x1""x2""x3"是fastbw()
Basically I was trying to do a stepwise selection of variables using fastbw()
in the rms package. I would like to pass the list of variables selected by fastbw()
into a formula as y ~ x1+x2+x3
, "x1" "x2" "x3" being the list of variables selected by fastbw()
这是我尝试但不起作用的代码
Here is the code I tried and did not work
olsOAW0.r060 <- ols(roll_pct~byoy+trans_YoY+change18m,
subset= helper=="POPNOAW0_r060",
na.action = na.exclude,
data = modelready)
OAW0 <- fastbw(olsOAW0.r060, rule="p", type="residual", sls= 0.05)
vec <- as.vector(OAW0$names.kept, mode="any")
b <- paste(vec, sep ="+") ##I even tried b <- paste(OAW0$names.kept, sep="+")
bestp.OAW0.r060 <- lm(roll_pct ~ b ,
data = modelready,
subset = helper =="POPNOAW0_r060",
na.action = na.exclude)
我是R的新手,但仍然没有走过陡峭的学习曲线,因此对明显的编程失误表示歉意.
I am new to R and still haven't trailed the steep learning curve, so apologize for obvious programming blunders.
推荐答案
您快到了.您只需要一起paste
整个公式,就像这样:
You're almost there. You just have to paste
the entire formula together, something like this:
paste("roll_pct ~ ",b,sep = "")
使用as.formula
将其强制为实际公式,然后将 that 传递给lm
.从技术上讲,我认为lm
可能会强制转换字符串本身,但是通常自己更强制转换为字符串. (某些期望公式的函数不会为您提供强制性,其他函数则可以.)
coerce it to an actual formula using as.formula
and then pass that to lm
. Technically, I think lm
may coerce a character string itself, but coercing it yourself is generally safer. (Some functions that expect formulas won't do the coercion for you, others will.)
这篇关于将变量向量传递给lm()公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!