[英]lapply for list comparisons in R
My first 3 lines of R code below work fine. 我下面的前3行R代码可以正常工作。 But when I make these 3 lines into a function, I get the
Error in m[[i + 1]] : subscript out of bounds
. 但是,当我将这3行变成一个函数时,我得到了
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). 您的lapply语句将从
m
的第一个索引(1)到最后一个索引(在这种情况下为L
)。 So, when you try to call m[[i+1]]
, you're calling an index that is not part of m
. 因此,当您尝试调用
m[[i+1]]
,您正在调用的索引不属于m
。 If m
has a length of 5, then you're call m[[5+1]]
, which is out of bounds. 如果
m
的长度为5,则您将调用m[[5+1]]
,这是超出范围的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.