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.
No comments:
Post a Comment