R如何使循环更快 [英] R how to make loop faster
本文介绍了R如何使循环更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似下面的代码,其中包含两个循环.该代码读取每月的流数据并将其复制为多个.循环是如此之慢.我想知道是否还有其他方法可以使其更快?
I have a code like below that contains two loops. The code reads monthly streamflow data and makes it as multi-replicate. The loops are so slow. I was wondering if there is any alternative way to make it faster?
library(xlsx)
library(data.table)
a <- read.xlsx("streamflow.xlsx",sheetName = "Sheet1", header = TRUE)
b=matrix(nrow=129792,ncol=17)
b= data.frame(b)
i=0
for (j in -11:1236)
{
for (k in 1:104)
{
i=i+1
j=j+12
j[j > 1248] <-j-1248
b[i,] <-a[j,]
}
}
谢谢
推荐答案
我相信这是将double for循环正确转换为矢量化代码的方法.它应该大大提高速度.另外,无需将b
声明为矩阵并将其转换为data.frame,只需从a
获取值即可.
I believe this is a proper translation of your double for-loop into vectorized code. It should increase the speed dramatically. Also, there is no need to declare b
as a matrix and convert it to a data.frame, the values can just be obtained from a
.
j_iter <- -11:1236
k_iter <- 1:104
k <- seq(12, length(k_iter) * 12, 12)
k <- rep(k, times=length(j_iter))
j <- rep(j_iter, each=length(k_iter))
j <- j + k
j[j > 1248] <- j[j > 1248] - 1248
b <- a[j,]
这篇关于R如何使循环更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文