This is a great example of when sapply is less efficient than loops. Although sapply makes code tidier, you pay for that tidiness over time.
Instead, you can wrap a while loop inside a for loop inside a nice, neat function.
Here are tests comparing a nested application loop with a nested while-while loop (and a mixed while-while loop, for a good grade). Update: Added vapply..match.. , indicated in the comments. Faster than simple, but still much slower than the while loop.
REFERENCE:
test elapsed relative 1 for.while 0.069 1.000 2 sapply.while 0.080 1.159 3 vapply.match 0.101 1.464 4 nested.sapply 0.104 1.507
Note that you save a third of your time ; The savings are likely to be greater if you start adding sequences to A.
For the second part of your question:
If you have it all completed in a nice feature, it's easy to add seq to A
Finally, if you want instead to find values ββof B less than A, just replace the operation in the function.
(You can include an if clause in a function and use only one function. I find it more efficient to have two separate functions)
findIndx.gt(A, B) # [1] 3 3 5 5 6 NA 8 NA NA findIndx.lt(A, B) # [1] 2 4 4 NA 8 7 NA NA NA
Then you can wrap it in one beautiful pacakge
rangeFindIndx(A, B, S) # AS indxB.gt indxB.lt # 10 1 3 2 # 5 1 3 4 # 3 1 5 4 # 4 1 5 NA # 7 1 6 NA # 100 1 NA NA # 2 1 NA NA # 10 4 6 4 # 5 4 3 4 # ...
Functions
(Note that they are dependent on reshape2 )
rangeFindIndx <- function(A, B, S) {
Ricardo saporta
source share