我试图在 for 循环中为几个不同的模型创建 AIC 分数。我已经为每个模型创建了一个具有对数似然性的 for 循环。但是,我坚持创建 lm 函数,以便它为我的列 LOGABUNDANCE 与我的数据帧的列 4 到 11 的每个组合计算一个模型。这是我到目前为止使用的代码。但这给了我每个模型类似的 AIC 分数。
# AIC score for every model
LL <- rep(NA, 10)
AIC <- rep(NA, 10)
for(i in 1:10){
mod <- lm(LOGABUNDANCE ~ . , data = erfly)
sigma = as.numeric(summary(mod)[6])
LL[i] <- sum(log(dnorm(erfly$LOGABUNDANCE, predict(mod), sigma)))
AIC[i] <- -2*LL[i] + 2*(2)
}
每个模型都会获得相同的 AIC,因为您创建了 10 个相等的模型。
为了使代码正常工作,您需要在每次迭代中更改模型的某种方式。
我可以看到两个选项:
在每次迭始时的数据子集,所以它只包含LOGABUNDANCE
和一个其他变量(如注释中的 @ yacine-hajji 建议),或者
创建要用于创建模型的变量的向量,并使用as.formula()
和paste0()
为每次迭代创建一个新公式。
我认为解决方案 2 更容易,这里是解决方案 2 的工作示例,使用mtcars
:
# AIC score for every model
LL <- rep(NA, 10)
AIC <- rep(NA, 10)
# Say I want to model all variables against `mpg`:
# Create a vector of all variable names except mpg
variables <- names(mtcars)[-1]
for(i in 1:10){
# Note how the formula is different in each iteration
mod <- lm(
as.formula(paste0("mpg ~ ", variables[i])),
data = mtcars
)
sigma = as.numeric(summary(mod)[6])
LL[i] <- sum(log(dnorm(mtcars$mpg, predict(mod), sigma)))
AIC[i] <- -2*LL[i] + 2*(2)
}
输出:
AIC
#> [1] 167.3716 168.2746 179.3039 188.8652 164.0947 202.6534 190.2124 194.5496
#> [9] 200.4291 197.2459
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(24条)