Search code examples
rminselfuniform

Find first increasing value in vector


I draw a random sample from Uniform Distribution by

u <- runif (1000,0,1)

Now I want to calculate the value of this random variable

N = min_n {n : u_n > u_{n-1}}

Edit Let say I draw a random sample of size 10.

So, I have u= (u_1,u_2,u_3,...,u_10). Now I want to find minimum n for which u_n > u_{n-1}


Solution

  • If you take the difference (using diff) then you're looking for where the difference is greater than 0. We search for the first time that happens

    u <- c(.5, .4, .3, .6)
    min(which(diff(u) > 0))
    

    This gives us 3 which is close to what we want but not exactly. Since this will return 1 if the first difference is greater than 0 what we really want to do is add 1 to the result

    min(which(diff(u) > 0))) + 1
    

    which should give what we want. This will give a warning if your sequence is strictly descending though since it can't find a value that meets the criteria. We could code in some tests and decide on the appropriate output in that case but I'll leave that as an exercise for the reader.