Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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,]
   }
 }

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
181 views
Welcome To Ask or Share your Answers For Others

1 Answer

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,]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...