简体   繁体   English

如何遍历glm测试不同的模型

[英]How to loop over glm testing different models

I have a vector a which contains some combinations of my variables. 我有一个向量a ,其中包含我的变量的一些组合。 In order to get the best possible model (smallest BIC), I hoped to be able to loop over the glm function - well, that didn't work. 为了获得最佳模型(最小的BIC),我希望能够遍历glm函数-嗯,那glm

The data looks something like this: 数据看起来像这样:

de.dat <- data.frame(death=c(0,0,0,1,0), ac=c(1, 2, 2, 3, 2), fv=c(1,0,0,0,1), vs=c(0,0,0,0,0), v2=c(0,0,1,1,1), ms=c(0,0,0,0,0), yv=c(0,0,1,0,1))

vars <- c("ac", "fv", "vs", "v2", "ms", "yv")
a <- apply(data.frame(t(combn(vars, 5))), 1, paste, collapse="+")

The model should look like this, with the dependent variable death and the independent variables of each element of a : 该模型应如下所示,具有因变量deatha的每个元素的自变量:

glm(death ~ a, data=de.dat, family="binomial")

In order to get the best model, I then need to extract the BIC of every model and then to be able to identify which BIC belongs to which model. 为了获得最佳模型,我需要提取每个模型的BIC,然后才能确定哪个BIC属于哪个模型。 Thank in advance. 预先感谢。

This one should help you. 这应该可以帮助您。 Here is your data: 这是您的数据:

de.dat <- data.frame(death=c(0,0,0,1,0), ac=c(1, 2, 2, 3, 2), fv=c(1,0,0,0,1), vs=c(0,0,0,0,0), v2=c(0,0,1,1,1), ms=c(0,0,0,0,0), yv=c(0,0,1,0,1))
vars <- c("ac", "fv", "vs", "v2", "ms", "yv")

You should create character vector with whole formula inside (not only the right part): 您应该在内部使用整个公式创建字符向量(不仅是正确的部分):

a <- apply(cbind(paste(names(de.dat)[1],"~"),data.frame(t(combn(vars, 5)))), 1, paste, collapse="+")

Then, using lapply function you can create a list, which consists of all your 6 models: 然后,使用lapply函数可以创建一个列表,其中包含所有6个模型:

models <- lapply(a,FUN = function(X) glm(X, data=de.dat, family="binomial"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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