Let's make a small example first, that computes in R:
x<- c(1,3,1,4,2)
max(which(x<2))
[1] 3
Now, I would like to do this not just for one value 2, but for many values simultaneously. It should give me something like that:
max(which(x<c(1,2,3,4,5,6)))
[1] NA 3 5 5 5 5
Of course I could run a for
loop, but that is very slow:
for(i in c(1,2,3,4,5,6)){
test[i]<-max(which(x<i))
}
Is there a fast way to do this?
A fully vectorized approach:
The advantages of full vectorization really start to kick in when both
x
andy
are relatively long and each contains many distinct values:Try this:
You can use
Vectorize
:Are you looking for this?
Find the max index of each value seen in
x
:Rearrange
Select from those:
It handily reports the values (in the first row) along with the indices (second row).
The
sapply
way is simpler and probably not slower:Benchmarks. The OP's case is not fully described, but here are some benchmarks anyway:
(@MrHallo's and @DavidArenburg's throw a bunch of warnings the way I have them written now, but that could be fixed.) Here are some results:
Of course, comparisons might come out differently for the OP's true case.