Reputation: 33
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?
Upvotes: 0
Views: 251
Reputation: 388982
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
Upvotes: 1