Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: finding column with minimum value in each row when there is a tied

Tags:

r

matrix

Here is my data example:

>dat <- matrix(c(59,50,48,44,44,NA,78,59,42,67,51,NA,72,64,64),byrow=TRUE,ncol=3) 
>k <- apply(dat, 1, function(x) which(x == min(x, na.rm = TRUE)))
>k
[[1]]
[1] 3

[[2]]
[1] 1 2

[[3]]
[1] 3

[[4]]
[1] 2

[[5]]
[1] 2 3

But, I want the output like this:

k
3 2 3 2 3

Many thanks in advance.

like image 370
lynn Avatar asked Feb 24 '23 16:02

lynn


1 Answers

do you want a maximum index for each row?
then,

> k <- apply(dat, 1, function(x) max(which(x == min(x, na.rm = TRUE))))
> k
[1] 3 2 3 2 3

will do that.

like image 60
kohske Avatar answered Feb 27 '23 16:02

kohske