写入函数来替换R中的循环

时间:2017-06-11 21:57:48

标签: r for-loop lapply

我的for循环代码遍历每一行,并将每个预测变量值乘以系数值:

lpb1B$HKGLMM <- NA
for (i in 1:nrow(lpb1B)) { 
lpb1B$HKGLMM[i] <- 
(exp(-93.7016 + (2.76336 * lpb1B$Depth[i]) 
+ (-0.02  * (lpb1B$Depth[i] * lpb1B$Depth[i])) 
+ (-0.00003 * lpb1B$Dist[i]) 
+ (-0.0059 * lpb1B$Aspect[i]))) / (1 + exp(-93.7016 + (2.76336 * lpb1B$Depth[i]) 
+ (-0.02  * (lpb1B$Depth[i] * lpb1B$Depth[i])) 
+ (-0.00003 * lpb1B$Dist[i]) 
+ (-0.0059 * lpb1B$Aspect[i])))
}

现在这是一些杂乱,冗长的代码。我还没有找到一个使用apply()的例子来帮助我避免这个循环。有没有办法绕过这个怪物循环?

2 个答案:

答案 0 :(得分:4)

你可以通过将系数向量乘以模型矩阵(即带有数据的矩阵作为列)的问题将其重新设置得更紧凑(如果你愿意)。唯一可能棘手的部分是匹配系数的顺序和模型矩阵的列...

使用@ Phil的例子:

lpb1B <- data.frame(
   Depth = sample(1:100, 20, replace = TRUE),
   Dist  = sample(1:100, 20, replace = TRUE),
   Aspect = sample(1:100, 20, replace = TRUE)
 )
 X <- model.matrix(~Dist+Aspect+Depth+I(Depth^2),lpb1B)

检查列的顺序:

 colnames(X)
 ## [1] "(Intercept)" "Dist"        "Aspect"      "Depth"       "I(Depth^2)"

构造匹配的参数向量:

 beta <- c(-93.7016,-0.00003,-0.0059,2.76336,-0.02)

然后(使用plogis(x)代替exp(x)/(1+exp(x)),这封装了你的循环:

 lpb1B$HKGLMM <- plogis(X %*% beta)

答案 1 :(得分:2)

完全符合@yannis的回答:

lpb1B <- data.frame(
  Depth = sample(1:100, 20, replace = TRUE),
  Dist  = sample(1:100, 20, replace = TRUE),
  Aspect = sample(1:100, 20, replace = TRUE),
  stringsAsFactors = FALSE
)
lpb1B$HKGLMM <- NA

lpb1B$HKGLMM <- 
  (exp(-93.7016 + (2.76336 * lpb1B$Depth) + 
         (-0.02  * (lpb1B$Depth * lpb1B$Depth)) +
         (-0.00003 * lpb1B$Dist) + 
         (-0.0059 * lpb1B$Aspect))) / 
  (1 + exp(-93.7016 + (2.76336 * lpb1B$Depth) + 
             (-0.02  * (lpb1B$Depth * lpb1B$Depth)) + 
             (-0.00003 * lpb1B$Dist) + 
             (-0.0059 * lpb1B$Aspect)))