R:与apply()和for循环混淆

R:与apply()和for循环混淆,r,R,我知道我应该避免for循环,但我不确定如何使用apply函数实现我想要的功能 这是一个稍微简化的模型,我正在尝试做什么。因此,本质上我有一个很大的预测矩阵,我想在索引预测的每一侧使用5个预测值的窗口来运行回归(在for循环的情况下是I)。对于for循环,我可以这样说: results<-NULL window<-5 for(i in 1:ncol(g)) { first<-i-window #Set window boundaries if(first<1

我知道我应该避免for循环,但我不确定如何使用apply函数实现我想要的功能

这是一个稍微简化的模型,我正在尝试做什么。因此,本质上我有一个很大的预测矩阵,我想在索引预测的每一侧使用5个预测值的窗口来运行回归(在for循环的情况下是I)。对于for循环,我可以这样说:

results<-NULL
window<-5
for(i in 1:ncol(g))
{
    first<-i-window #Set window boundaries
    if(first<1){
        1->first
    }
    last<-i+window-1
    if(last>ncol(g)){
        ncol(g)->last
    }
    predictors<-g[,first:last]

    #Do regression stuff and return some result
    results[i]<-regression stuff
}
window <- 5
ng <- 15 #or ncol(g)
xy <- data.frame(first = pmax( (1:ng) - window, 1 ), 
                  last = pmin( (1:ng) + window, ng) )

results在这种情况下,使用
apply
函数进行回归主要是一种偏好;它可以为您处理一些簿记(因此可能会防止错误),但不会加快代码的速度

不过,我建议使用矢量化函数来计算您的
第一个
最后一个
,可能类似于:

results<-NULL
window<-5
for(i in 1:ncol(g))
{
    first<-i-window #Set window boundaries
    if(first<1){
        1->first
    }
    last<-i+window-1
    if(last>ncol(g)){
        ncol(g)->last
    }
    predictors<-g[,first:last]

    #Do regression stuff and return some result
    results[i]<-regression stuff
}
window <- 5
ng <- 15 #or ncol(g)
xy <- data.frame(first = pmax( (1:ng) - window, 1 ), 
                  last = pmin( (1:ng) + window, ng) )
或者像这样使用
lappy

results <- list()
for(i in 1:nrow(xy)) {
  results[[i]] <- xy$first[i] : xy$last[i]
}
results
results <- lapply(1:nrow(xy), function(i) {
  xy$first[i] : xy$last[i]
})

results这个问题涉及到《R地狱》中的几个要点

有一些循环你应该避免,但不是所有的。使用apply函数更像是隐藏循环而不是避免循环。这个例子似乎是一个很好的选择,可以留在“for”循环中

增长对象通常是一种不好的形式——在某些情况下效率极低。如果你要有一个总括规则,那么“不增长对象”比“避免循环”更好

您可以通过以下方式创建具有最终长度的列表:

result <- vector("list", ncol(g))
for(i in 1:ncol(g)) {
    # stuff
    result[[i]] <- #results
}

result afaik是
apply
家族中的语法糖,它实际上并没有加快代码的速度。。。不完全正确。。值得注意的是,lapply有时会有非常好的加速效果。此外,语法糖可以帮助您分解复杂的循环和函数,以便只应用于需要它的组件。