在下面的R代码中,假设我想使用类似的R例程比较所有唯一的2 m
个对象。例如,要比较m1
和m2
,我的例程是:
pchisq(2 * (logLik(m2) - logLik(m1)), df = abs(m1$df.residual - m2$df.residual), lower = F)
问题:
我想知道如何使用我的例程对所有m
对象进行唯一的成对比较?
这是我尝试没有成功的事情:
## Suppose we have 4 `m` objects: `m1...m4` (6 unique pairwise comparisons possible)
m1 <- lm(hp ~ vs, mtcars)
m2 <- lm(hp ~ vs*wt, mtcars)
m3 <- lm(hp ~., mtcars)
m4 <- lm(hp ~ vs * gear * wt, mtcars)
compare <- function(...){
m <- list(...)
L <- length(m) - 1
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.tail = FALSE) )
}
# Example of use:
compare(m1, m2, m3, m4)
答案 0 :(得分:3)
您可以使用combn
来获取要比较的所有组合:
compare <- function(...){
m <- list(...)
n_mod <- length(m)
names(m) <- sapply(substitute(list(...))[-1], deparse)
combs <- t(combn(x = names(m), m = 2))
comp_value <- apply(X = combs, MARGIN = 1, function(ind) pchisq(2 * (logLik(m[[ind[2]]]) - logLik(m[[ind[1]]])), df = abs(m[[ind[1]]]$df.residual - m[[ind[2]]]$df.residual), lower.tail = FALSE))
df_out <- data.frame(combs, comp_value)
names(df_out) <- c("mod_1", "mod_2", "comp_value")
return(df_out)
}
因此,为了使读取结果更容易,您可以返回带有所有比较结果的data.frame
。
然后
compare(m1, m2, m3, m4)
mod_1 mod_2 comp_value
1 m1 m2 2.391012e-02
2 m1 m3 7.253068e-08
3 m1 m4 1.248692e-06
4 m2 m3 2.735901e-07
5 m2 m4 4.256098e-06
6 m3 m4 1.000000e+00