Search code examples
rdataframeuniquematchingminimum

Find minimum for every row in a dataframe stemming from a unique column


I need to find the row-wise minimum in an array where each minimum must stem from a unique column. For example, a is a dataframe/matrix

| X1 | X2|X3|
| 4  | 5 | 6|
| 1  | 2 | 3|
| 7  | 8 | 9|

When i use rowMin, the output is 4,1,7. However, what I need an output of is unique minimum of each row vs column. Therefore the output needs to be 5,1,9 I know there are solutions in python, Im unable to do this in R!


Solution

  • You could use recursion as follows:

    unique_min <- function(mat){
      if(NCOL(mat) == 1) min(mat)
      else c(min(mat[,1]), Recall(mat[-which.min(mat[,1]), -1]))
    }
    unique_min(df)
    [1] 1 5 9
    

    Note that the above is the results of doing columnwise instead of rowwise. If you do it rowwise:

     unique_min(t(df))
     [1] 4 2 9