Here is another way that has a better performance w.r.t. @Cath solutions:
a <- which(m, arr.ind = T)
colnames(m)[aggregate(col~row,a[order(a[,1]),],min)$col]
# [1] "A" "B" "C" "B" "B" "A"
Benchmarking given the matrix used by @Cath:
m0h3n <- function(m){
a <- which(m, arr.ind = T)
colnames(m)[aggregate(col~row,a[order(a[,1]),],min)$col]
}
all.equal(akrun(n), cath(n), joe(n), m0h3n(n))
# [1] TRUE
microbenchmark(akrun(n), cath(n), joe(n), m0h3n(n))
# Unit: microseconds
# expr min lq mean median uq max neval
# akrun(n) 2291.981 2395.793 2871.7156 2482.7790 3561.9150 4205.370 100
# cath(n) 8263.210 8554.665 9695.9375 8782.8710 9947.9415 58239.983 100
# joe(n) 274.029 298.517 526.6722 312.0375 342.5355 2366.798 100
# m0h3n(n) 3890.178 3974.309 4280.6677 4073.1635 4227.7550 6337.501 100
Therefore, here is the ranked solutions (in terms of efficiency):
- joe
- akrun
- m0h3n
- Cath