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

Time:06-02

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!

CodePudding user response:

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

CodePudding user response:

Another recursion

f <- function(n) {
    if (n == 1) {
        return(which.min(df[1:n, ]))
    }
    v <- Recall(n - 1)
    c(v, which.min(replace(df[n, ], v, Inf)))
}

df[cbind(f(nrow(df)), 1:ncol(df))]
# [1] 4 2 9
  • Related