Reputation: 83
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.
Upvotes: 0
Views: 71
Reputation: 25225
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))
Upvotes: 1