0

I have a vector X which can potentially contain a very large number of entries and I want to find the maximal index i such that X[i] <= a*i/m (for some constants a,m) and I'd really rather not loop over the vector. I thought about using Position but I can't figure out how to make a suitable function that would take into account the indexes of the vector.

I forgot to mention that the entries of the vector will be sorted so that might help.

Help would be appreciated

Serpahimz
  • 175
  • 1
  • 8
  • 2
    You are much more likely to receive a helpful answer if you provide a [**minimal, reproducible example**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) including input data, the desired result, and the code you have tried and why it didn't work. – Henrik Mar 28 '14 at 11:22

2 Answers2

2

I interpret your question (as of "right now" ) differently from ChinmayP, so maybe this:

foo <- which ( X/(1:(length(X)) < a/m)

rev(foo)[1]

That will give you the element of X with the largest index i (as in X[i] ) which meets your condition.

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
1

Following should give you what you want.

max(which(X <= a/m * seq_along(X)))

Looping backwards might still be better idea though, as you only want maximum index value.

for ( i in length(X):1 ) { if (X[i] <= a*i/m) break } ;  i 

When the loop breaks, i will contain your required max index.

CHP
  • 16,981
  • 4
  • 38
  • 57