Search code examples
rvectorlag

For each value in a vector get the corresponding next smallest value


For each element in a vector, I want the corresponding next smaller value in the vector, without changing the original order of the elements.

For example, suppose the given vector is:

c(4, 5, 5, 10, 3, 7)

Then the result would be:

c(3, 4, 4, 7, 0, 5)

Note that since 3 does not have any smaller value, I want it to be replaced with 0. Any help will be much appreciated. Thank you.


Solution

  • We may use

    sapply(v1, function(x) sort(v1)[match(x, sort(v1))-1][1])
    [1]  3  4  4  7 NA  5
    

    Or use a vectorized option

    v2 <- unique(v1)
    v3 <- sort(v2)
    v4 <-  v3[-length(v3)]
    i1 <- match(v1, v3) - 1
    i1[i1 == 0] <- NA
    v4[i1]
    [1]  3  4  4  7 NA  5
    

    data

    v1 <- c(4, 5, 5, 10, 3, 7)