0

I have a 100x5 matrix, let's call it d. Here are the contents of d:

         [,1]     [,2]     [,3]     [,4]      [,5]
[1,] 192.3273 152.8275 158.7368 199.9222 209.09283
[2,] 155.8720 157.3843 153.9376 248.1005 212.35851
[3,] 228.1295 130.2183 260.8789 314.3371  54.35375
[4,] 173.6735 111.3873 238.1540 194.9216 172.86597
[5,] 219.6467 276.0814 347.3341 345.8772 163.06900
[6,] 195.2154 223.5708 289.9555 288.3098 116.04556

I want to get the minimum value of each row, which I can get easily using

apply(d, 1, min)

What I also want to get is the column number of the minimum value. So a vector of values from 1-5 which correspond to minimum value in each row.

Additionally is there anything more efficient that the apply function?

Ben

ben890
  • 1,097
  • 5
  • 25
  • 56
  • `max.col(-m)` maybe. – Frank Apr 19 '16 at 16:00
  • Also good: `apply(d, 1, which.min)`. – Gregor Thomas Apr 19 '16 at 16:00
  • 1
    Here's one candidate for a dupe, though it goes further by considering ties: http://stackoverflow.com/q/5495289/ or http://stackoverflow.com/q/27404710/ or (regarding max) http://stackoverflow.com/q/17735859/ – Frank Apr 19 '16 at 16:01
  • 1
    And, just for reference, if you didn't know about those specialty functions, something like `apply(d, 1, function(x) which(x == min(x))[1])` should work too. – Gregor Thomas Apr 19 '16 at 16:04
  • I liked the second one because it's answer had everything mentioned here in the comments. Good find! – Gregor Thomas Apr 19 '16 at 16:06
  • Also is there anything more efficient that apply for apply(d, 1, min). I like max.col(-m) because of how efficient it is. – ben890 Apr 19 '16 at 16:10
  • Yeah, if you have a data.frame, `pmin` is the way to find row-mins. With a matrix, you'll maybe want the matrixStats package, which has a `rowMins` function: http://stackoverflow.com/q/6338517/ – Frank Apr 19 '16 at 16:11

0 Answers0