循环遍历R中的变量

时间:2016-02-26 11:40:33

标签: r function loops

我有一个结果数据,Y和10个预测因子(X1-X10)。

set.seed(1001)
n <- 100
Y < c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
X1 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.1,0.4,0.5))
X2 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.5,0.25,0.25))
X3 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.3,0.4,0.4))
X4 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.35,0.35,0.3))
X5 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.1,0.2,0.7))
X6 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.8,0.1,0.1))
X7 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.1,0.1,0.8))
X8 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.35,0.35,0.3))
X9 <- sample(x=c(0,1,2), size=n, replace=TRUE, prob=c(0.35,0.35,0.3))
X10 <- c(0,2,2,2,2,2,2,2,0,2,0,2,2,0,0,0,0,0,2,0,0,2,2,0,0,2,2,2,0,2,0,2,0,2,1,2,1,1,1,1,1,1,1,1,1,1,1,0,1,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0)

datasim <- data.frame(Y,X1,X2,X3,X4,X5,X6,X7,X8,X9,X10)

我的目标是为每个预测变量拟合逻辑模型并计算偏差差异(dDeviance)。然后引导dDeviance 1000次(R = 1000)。我尝试了以下函数,一次只能处理一个变量。你能否建议如何增强代码,使其循环变量1到10,计算dDeviance,然后再引导值。

glmfunction <- function(data,indices)
{
glm.snp1 <- glm(Y~X1, family="binomial", data=data[indices,])
null <- glm.snp1$null.deviance
residual <- glm.snp1$deviance
dDeviance <-(null-residual)
return(dDeviance)
}

result <- boot(datasim,glmfunction, R=1000)

1 个答案:

答案 0 :(得分:3)

可能有很多方法可以解决这个问题,但是我会怎样做。我首先创建一个我想在模型中使用的自变量向量:

#vector of independent variables
iv <- grep("X",colnames(datasim), value=T)

然后我循环它们以适应模型并提取dDeviance。这可以确保我的启动函数不会返回一个值,而是一个长度向量(独立变量的数量)。

glmfunction <- function(data,indices, iv){
  res <- sapply(iv, function(x){
    fit <- glm(formula=sprintf("Y~%s",x), family="binomial", data=data[indices,])
    #deviance
    dDeviance <- with(fit, null.deviance - deviance)
    return(dDeviance)
  })
  res
}

我选择使iv成为启动函数的正式参数,因此您必须指定它并且不会遇到意外的范围问题,以获得灵活性和更轻松的调试。然后你可以运行你的引导程序:

result <- boot(datasim,glmfunction, iv = iv, R=10)