简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM