Home > Mobile >  For each value in a vector get the corresponding next smallest value
For each value in a vector get the corresponding next smallest value

Time:01-07

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.

CodePudding user response:

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)

CodePudding user response:

We can try the code below using outer max.col

> m <- outer(v, u <- sort(unique(v)), `>`)

> replace(u[max.col(m, ties.method = "last")], rowSums(m) == 0, NA)
[1]  3  4  4  7 NA  5

CodePudding user response:

Using findInterval:

sx = sort(x)
i = findInterval(x, sx, left.open = TRUE)
sx[replace(i, i == 0, NA)]
# [1]  3  4  4  7 NA  5
  •  Tags:  
  • Related