[R] for loop for extracting linear model info

Uwe Ligges ligges at statistik.tu-dortmund.de
Sat Apr 4 23:48:56 CEST 2009



Melissa2k9 wrote:
> 
> 
> Uwe Ligges-3 wrote:
>>
>>
>> Melissa2k9 wrote:
>>> Hi,
>>>
>>> I have written a for loop as such:
>>>
>>> model<-lm(Normalised~Frame,data=All,subset=((Subject==1)&(Filmclip=="Strand")))
>>> summary(model)
>>>
>>> #######################################
>>> #To extract just the Adjusted R squared
>>> #######################################
>>>
>>> rsq<-summary(model)[[9]]
>>>
>>> ###########################
>>> #To extract just the slope
>>> ###########################
>>>
>>> slope<-summary(model)[[4]][[2]]
>>>
>>> #######################################################
>>> #To extract only the p value from the t test for slope
>>> #######################################################
>>>
>>> pvalue<-summary(model)[[4]][[8]]
>>>
>>> ####################################
>>> data<-data.frame(slope,pvalue,rsq)
>>> ####################################
>>>
>>>
>>> #######################################
>>> #To extract this info for all films
>>> ########################################
>>>
>>> for (i in c(1:8,10:20,22:29))
>>> {
>>> model_1<-lm(Normalised~Frame,data=All,subset=((Subject==i)&(Filmclip=="Strand")))
>>> summary(model_1)
>>> slope<-summary(model_1)[[4]][[2]]
>>> pvalue<-summary(model_1)[[4]][[8]]
>>> rsq<-summary(model_1)[[9]]
>>> data2<-data.frame(slope,pvalue,rsq)
>>> data2<-rbind(data,data2)
>>> }
>>>
>>> I want this to run for all i but so far I am only getting two entries in
>>> my
>>> data frame, one for the first subject, and another.
>>
>> You are overwriting the old data2 with a new one that consists of those 
>> two in each iteration of the loop .......
>>
>>
>> Uwe Ligges
>>
>>
>>> Does anyone know where I am going wrong in my code so I can have this
>>> data
>>> for all subjects 1-8,10-20, and 22-29.
>>>
>>> Thanks
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>>
> 
> 
> 
> 
> 
> Hey,
> 
> Thanks, but do you have any advice on how to stop overwriting the old data2
> and just keep adding a new row for each different subject?
> 
> Thanks :)


Untested, because you have still not given a reproducible examples which 
the posting guide asks you to do:

indices <- c(1:8,10:20,22:29)
li <- length(indices)
data2 <- data.frame(slope=numeric(li), pvalue=numeric(li), rsq=numeric(li))
for (i in seq_along(indices)){
  model_1 <- lm(Normalised ~ Frame, data = All, subset = 
((Subject==indices[i]) & (Filmclip=="Strand")))
  summod_1 <- summary(model_1)
  slope <- summod_1[[4]][[2]]
  pvalue <- summod_1[[4]][[8]]
  rsq <- summod_1[[9]]
  data2[i,] <- c(slope, pvalue, rsq)
  }



Uwe Ligges




More information about the R-help mailing list