Skip to content

Instantly share code, notes, and snippets.

@randrescastaneda
Last active October 3, 2019 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randrescastaneda/2ba31f1f3f2156c7ed0d27ea0331316e to your computer and use it in GitHub Desktop.
Save randrescastaneda/2ba31f1f3f2156c7ed0d27ea0331316e to your computer and use it in GitHub Desktop.
N highest of vector. This function was created by [Zach](https://stackoverflow.com/users/345660/zach) in this [post](https://stackoverflow.com/questions/2453326/fastest-way-to-find-second-third-highest-lowest-value-in-vector-or-column). I just keep it here for storage purposes.
maxN <- function(x, N=2, decreasing = FALSE){
len <- length(x)
if(N>len){
warning('N greater than length(x). Setting N=length(x)')
N <- length(x)
}
if (decreasing == FALSE) {
sort(x,partial=len-N+1)[len-N+1]
} else {
-sort(-x,partial=len-N+1)[len-N+1]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment