小编sir*_*ugg的帖子

如何使用vecorization替换for循环每个data.frame行数千次?

对于关于R和 - 更重要的 - 矢量化的耳朵仍然非常潮湿,我无法理解如何加速下面的代码.

for循环通过对每个种子应用随机可能性来计算落入具有不同密度的种子生成植物的若干路段的道路上的种子数量.由于我的真实数据帧有大约200k行,种子数量高达300k /段,使用下面的示例在我当前的机器上需要几个小时.

#Example data.frame
df <- data.frame(Density=c(0,0,0,3,0,120,300,120,0,0))
#Example SeedRain vector
SeedRainDists <- c(7.72,-43.11,16.80,-9.04,1.22,0.70,16.48,75.06,42.64,-5.50)

#Calculating the number of seeds from plant densities
df$Seeds <- df$Density * 500

#Applying a probability of reaching the road for every seed
df$SeedsOnRoad <- apply(as.matrix(df$Seeds),1,function(x){
    SeedsOut <- 0
    if(x>0){
        #Summing up the number of seeds reaching a certain distance
        for(i in 1:x){
            SeedsOut <- SeedsOut +
                ifelse(sample(SeedRainDists,1,replace=T)>40,1,0)
        }
    }
    return(SeedsOut)
})
Run Code Online (Sandbox Code Playgroud)

如果有人可能会给我一个关于如何用矢量化代替循环的提示 - 或者可能首先如何更好地组织数据以提高性能 - 我将非常感激!

编辑:罗兰的回答表明我可能过于简化了问题.在for-loop中,我从另一位作者记录的距离分布中提取一个随机值(这就是我不能在这里提供数据的原因).添加了具有SeedRain距离的可能值的示例性矢量.

performance for-loop r vectorization

4
推荐指数
1
解决办法
143
查看次数

标签 统计

for-loop ×1

performance ×1

r ×1

vectorization ×1