Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@noamross
Last active January 21, 2016 00:11
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 noamross/2032675 to your computer and use it in GitHub Desktop.
Save noamross/2032675 to your computer and use it in GitHub Desktop.
Ways to find the N minimum value in a vector
#Looking for a fast way to find the N minimum values in a vector of values. For use in finding nearest neighbors when one already has a (large) distance matrix.
x <- runif(5000)
n <- 3
system.time({ # What I'm using now
for(i in 1:10000) {
a <- sort(x)[1:n]
b <- match(a, x)
}
})
@davharris
Copy link

# This saves a quarter of a second.  Can you vectorize your 10000 replicates?

system.time({            
  for(i in 1:10000) {
    order(x)[seq.int(n)]
  }
})

# Edit: this seems like it might even be slightly faster:

values = seq.int(n)

system.time({            
  for(i in 1:10000) {
    a = .Internal(order(na.last = TRUE, decreasing = FALSE, x))[values]
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment