0

I have some value of x:

x <- c(12, 5, 6, 7, 8, 5, 8, 7, 5, 6, 9, 10)
p <- x[order(x)]
p
[1]  5  5  5  6  6  7  7  8  8  9 10 12

The smallest value of x is 5, but I want to choose the second of the smallest x (6) or third (7).

How to get it?

neilfws
  • 32,751
  • 5
  • 50
  • 63
giarno
  • 33
  • 4
  • Thought it might be a duplicate of [Fastest way to find second (third…) highest/lowest value in vector or column](https://stackoverflow.com/questions/2453326/fastest-way-to-find-second-third-highest-lowest-value-in-vector-or-column) but looks slightly different. – thelatemail Mar 20 '18 at 05:21

1 Answers1

1

We can write a function to get nth smallest value, by considering only unique values of already sorted vector p.

get_nth_smallest_value <- function(n) {
   unique(p)[n]
}

get_nth_smallest_value(2)
#[1] 6

get_nth_smallest_value(4)
#[1] 8

Or if we need in terms of only x, we can sort them first, take only unique values and then get the value by it's index.

get_nth_smallest_value <- function(n) {
  unique(sort(x))[n]
}

get_nth_smallest_value(2)
#[1] 6

get_nth_smallest_value(3)
#[1] 7
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • The question I linked above also suggests - `sort(unique(x),partial=n)[n]` which might eek out a tiny bit of efficiency. – thelatemail Mar 20 '18 at 05:28
  • @thelatemail I am not aware about how `partial` argument works. However, if you think it's a duplicate feel free to hammer it. – Ronak Shah Mar 20 '18 at 05:31
  • I don't think it's a duplicate - it's just very similar. The `partial=` just avoids needing to sort the whole thing as far as I can tell. – thelatemail Mar 20 '18 at 05:32