将lm()插入R中的for循环

时间:2015-12-05 23:09:31

标签: r for-loop lm

新的编码员,长时间潜伏的第一次海报,所以这个问题可能会非常糟糕......

对于概念证明,我试图在R中的for循环中运行lm(),然后对该lm()执行anova()。我的数据集中感兴趣的变量是产量,实践和治疗。我的练习中有2个级别," PL"和" LT",并希望两次运行lm(产量〜练习*治疗);当练习=" PL"并且一次当练习=" LT",然后anova()这两个lm()' s。

我以前从未在R中做过循环,到目前为止我有:

for (i in 1:2) {lm(Yield~Practice[i]*Treatment)}

如何调整它以便在循环的第一次迭代中调用第一级练习(PL),然后在第二次迭代中调用第二级(LT)?然后我也想将anova()写入循环中。

我知道通过练习然后运行2个anova()会更容易,因为在实践中只有2个级别,但是,我只是练习并且希望看到如何为将来的应用做到这一点。谢谢!

1 个答案:

答案 0 :(得分:0)

第1步:创建一个包含practice

值的唯一集合
#assume all you variables are in `data`
lvl_Practice<- unique(data$Practice)

Step2:循环

for ( i in 1:length(lvl_Practice) ){
    #create a subset data 
    data_sub <- subset(data,Practice== lvl_Practice[i])

    #create the linear model. If it is the first loop,
    #then the model name will be lm1
    assign(paste("lm",i),lm(Yield~Practice*Treatment,data=data_sub))
}

如果lm1中只有2个级别,则此方法会为您lm2practice

编辑06/12/2015

根据以下@ eipi10的评论,答案可以修改为:

for ( i in unique(data$Practice) ){
    #create a subset data 
    data_sub <- subset(data,Practice== i)

    #Note1: create the linear model. If it is the first loop,
    #then the model name will be lm1.
    #Note2: There is no need to put `Practice` factor in the model  
    assign(paste("lm",i),lm(Yield~Treatment,data=data_sub))
}

编辑09/12/2015

根据我的评论,答案可以修改为:

for ( i in unique(data$Practice) ){
    #create a subset data 
    data_sub <- subset(data,Practice== i)

    #Note1: create the linear model. If it is the first loop,
    #then the model name will be lmPL and lmLT.
    #Note2: There is no need to put `Practice` factor in the model  
    assign(paste("lm",i,sep=""),lm(Yield~Treatment,data=data_sub))
}