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)

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 his blog: compBiomeBlog.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



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.