Andy Petran
Andy Petran

Reputation: 11

plugging an lm() into a for loop in R

New coder, long time lurker first time poster, so this question is probably going to be really nooby and bad....

For a proof of concept i'm attempting to run an lm() in a for loop in R, and then perform an anova() on that lm(). The variables of interest in my dataset are yield, practice and treatment. I have 2 levels in my practice, "PL" and "LT", and would like to run an lm(yield~practice*treatment) twice; once for all observations when practice = "PL" and and once for when practice = "LT", then anova() both of those lm()'s.

I've never done loops in R before, so far I have:

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

How do I adjust this so that it calls just the first level of Practice (which is PL) in the first iteration of the loop and then the second level(LT) in the second iteration? Then I'd like to write the anova() into the loop as well.

I know itd be easier just to subset() by Practice and then run 2 anova()'s, since theres only 2 levels in practice, but, I'm just practicing and would like to see how this is done for future application. Thanks!

Upvotes: 0

Views: 6152

Answers (1)

Sixiang.Hu
Sixiang.Hu

Reputation: 1019

Step1: create a unique set including values from practice

#assume all you variables are in `data`
lvl_Practice<- unique(data$Practice)

Step2: loop

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))
}

This method will give you lm1 and lm2 if there are only 2 levels in the practice.

Edit 06/12/2015

According to the comment from @eipi10 below, the answer can be revised as:

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))
}

Edit 09/12/2015

According to the comment from mine below, the answer can be revised as:

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))
}

Upvotes: 1

Related Questions