将变量向量传递给lm()公式

我试图使我的代码片段自动化,以使编程变得不再那么乏味。


基本上,我试图fastbw()在rms包中使用逐步选择变量。我想将选择的变量列表传递fastbw()到公式中y ~ x1+x2+x3,因为“ x1”“ x2”“ x3”是选择的变量列表fastbw()


这是我尝试但无法正常工作的代码


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语言的新手,仍然没有走过陡峭的学习曲线,因此对明显的编程失误表示歉意。


守着星空守着你
浏览 714回答 3
3回答

侃侃无极

你快到了。你只需要paste在整个配方一起,像这样:paste("roll_pct ~ ",b,sep = "")使用将其强制转换为实际公式as.formula,然后将其传递给lm。从技术上讲,我认为lm可以强制字符串本身,但是通常自己更强制。(某些期望公式的函数不会为您提供强制性,其他函数则可以。)

ITMISS

我今天遇到了类似的问题,如果您想使其更加通用,甚至不需要固定的类名,则可以使用frmla <- as.formula(paste(colnames(modelready)[1], paste(colnames(modelready)[2:ncol(modelready)], sep = "",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; collapse = " + "), sep = " ~ "))假定您在第一列中具有类变量或因变量,但索引可以很容易地切换到最后一列,如下所示:frmla <- as.formula(paste(colnames(modelready)[ncol(modelready)], paste(colnames(modelready)[1:(ncol(modelready)-1)], sep = "",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; collapse = " + "), sep = " ~ "))然后继续lm使用:bestp.OAW0.r060 <- lm(frmla , data = modelready, ... )
打开App,查看更多内容
随时随地看视频慕课网APP