R tip: Finding the location of minimum and maximums

February 26, 2010
By

[This article was first published on compBiomeBlog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I can never remember this R command, so I am going to post it here which probably means I will always remember it and never have to look it up here again.

I sometimes want to find the location of a minimum or maximum value in a vector, so I can look up the corresponding position in another vector, or column or something. You can just use order but that is a bit clunky and more prone to error, so what you really need is which.min and which.max.

x <- sample(1:100,20)
which.min(x)

x <- matrix(sample(1:100,20),nrow=10)
x[which.min(x[,2]),1]

Not exactly earth-shatteringly useful but better than:

x <- matrix(sample(1:100,20),nrow=10)

x[order(x[,2])[1],1]

Or is it? Now I write that, it is actually less characters than which.min. Oh well.

To leave a comment for the author, please follow the link and comment on their blog: compBiomeBlog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)