I've got a lot of matrices similar to this but with thousands of rows :
r <- 10
c <- 2
set.seed(333)
m1 <- matrix(runif(r*c)+1, r, c)
> m1
[,1] [,2]
[1,] 1.467001 1.393902
[2,] 1.084598 1.474218
[3,] 1.973485 1.891222
[4,] 1.571306 1.665011
[5,] 1.020119 1.736832
[6,] 1.723557 1.911469
[7,] 1.609394 1.637850
[8,] 1.306719 1.864651
[9,] 1.063510 1.287575
[10,] 1.305353 1.129959
I've got a loop that tells me, for each value of the first column, what is the index of the first value in the second column that is 10% higher like so :
result <- 1:nrow(m1)
for (i in 1:nrow(m1)){
result[i] <- which(m1[,2]>(1.1*m1[,1][i]))[1]
}
> result
[1] 3 1 NA 3 1 6 3 2 1 2
I've got so much matrices that it's taking hours, and after profiling my code, the biggest time consuming task by far is this loop. What is, according to you, the fastest way to do it ?
For example, with r = 30000 :
start_time <- Sys.time()
for (i in 1:nrow(m1)){
result[i] <- which(m1[,2]>(1.1*m1[,1][i]))[1]
}
end_time <- Sys.time()
a <- end_time - start_time
> a
Time difference of 11.25815 secs
Thanks for you help !