Skip to content

for loop for extracting linear model info

4 messages · Melissa2k9, Uwe Ligges

#
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.

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
#
Melissa2k9 wrote:
You are overwriting the old data2 with a new one that consists of those 
two in each iteration of the loop .......


Uwe Ligges
#
Uwe Ligges-3 wrote:
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 :)
1 day later
#
Melissa2k9 wrote:
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