简体   繁体   中英

Optimizing the speed of loop in a xts format in R

I have a data structured as xts like bellow: 在此处输入图像描述

The dimension is 2298 rows and 30 columns. I want to do a loop in each row and column and store it in a new matrix/data frame. Considering the xts data as variable a, the sample code would be:

for(i in 1:nrow(a)){
 b[i,1] <- a[i,1]
  for(j in 2:ncol(a)){
   b[i,j] <- ((1+a[i,j])^j/(1+b[i,j-1]))-1
  }
}

As for loops are really slow in R, I wonder how can I speed this function up.

I think the slowness is due to the fact that you have not allocated memory for b before running the loop and also R uses vectorized operations and hence the i loop is not required:

system.time({
  b <- matrix(0, nrow(a), ncol(a))
  b[,1] <- a[,1]
  for(j in 2:ncol(a)){
    b[,j] <- ((1+a[,j])^j/(1+b[,j-1]))-1
  }
})
#   user  system elapsed 
#      0       0       0 

data:

#R-3.6.1 64bit Win10
set.seed(0L)
nr <- 2298L
nc <- 30L
library(xts)
a <- xts(matrix(rnorm(nr*nc), nr, nc), seq(Sys.Date()-nr, by="1 day", length.out=nr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM