Question

I found a useful function that I have been using in R to access the F-statistic p-values from a linear model

lmp<-function(modelobject){

if(class(modelobject !="lm" stop ("Not an object of class 'lm ")
f<-(modelobject)$fstatistic
p<-pf(f[1],f[2],f[3],lower.tail=F)
attributes(p)<-NULL
return(p)

}

However, the data that I need to use this function is not an object of class lm rather a list with 12 elements. Each element of the list is the summary generated from lm. Each summary in the list data, can be accessed using

data[[1]]$fstatistic

I want to change the function to loop over each element in the list and return the F-statistic p-value, I tried modifying the function to include a for loop, lmpmod<-function(modelobject){

for (i in 1:12) {
f<-(modelobject)[[i]]$fstatistic
p<-pf(f[1], f[2], f[3], lower.tail=F)
attributes(p)<-NULL
return(p)

}
}    

but the output keeps over-writing itself. Can anyone tell me how to modify this function so that I can access each element in the list and calculate the F-statistic p-value?

Was it helpful?

Solution

Try

lapply( data , function(x) { tmp <-  summary(x)$fstatistic ;
                             pf( tmp[1] , tmp[2] , tmp[3] , lower.tail = F )
                             } )

For example...

#  non-sensical lm!
set.seed(123)
y <- 1 + rnorm(10)

#  this makes a list of 5 lm's using the response data 'y'
data <- replicate( 5 , lm(  y ~ 1 + rnorm(10) ) , simpl = FALSE )

#  Call 'summary' on model object to calculate the f-statistic, and run 'pf' to get p-value
sapply( data , function(x) { f <- summary(x)$fstatistic ; pf(f[1], f[2], f[3], lower.tail=F) } )
     value      value      value      value      value 
0.53263166 0.03896285 0.70298727 0.57721440 0.45352619 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top