简体   繁体   中英

lapply for list comparisons in R

My first 3 lines of R code below work fine. But when I make these 3 lines into a function, I get the Error in m[[i + 1]] : subscript out of bounds .

Can this be fixed?

m1 <- lm(hp ~ vs, mtcars)
m2 <- lm(hp ~ vs*wt, mtcars)

pchisq(2 * (logLik(m2) - logLik(m1)), df = abs(m1$df.residual - m2$df.residual), lower = F)

###### Make a function of above 3 lines: ######

 compare <- function(...){

   m <- list(...)
   L <- length(m)

lapply(1:L, function(i) pchisq(2 * (logLik(m[[i+1]]) - logLik(m[[i]])), df = abs(m[[i]]$df.residual - m[[i+1]]$df.residual), lower = F) )
 }
 ## Example of use:
  compare(m1, m2)       # `Error in m[[i + 1]] : subscript out of bounds`

Your lapply statement is going from the first index (1) to the last index of m ( L , in this case). So, when you try to call m[[i+1]] , you're calling an index that is not part of m . If m has a length of 5, then you're call m[[5+1]] , which is out of bounds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM