Daniel James
Daniel James

Reputation: 1433

Print Column Name of Smallest Element of Each Row in R

I want R to print the column-name holding the minimum element in every row of a matrix.

Minimum Reproducible Example

################# Simulate 99 integers between 1 to 20 with replacement. ################
set.seed(1)
a <- sample.int(20, 99, replace = TRUE)
################## For a 9 by 11 matrix #####################
b <- matrix(a, ncol = 11)
colnames(b) <- 2:12
b
 ##       2  3  4  5  6  7  8  9 10 11 12
 ## [1,]  4 10  5  6  8 13 12 16  6  7 12
 ## [2,]  7 14  5 10 12 18  6 14 17 19  7
 ## [3,]  1 10  2 10  6 14  8 20  9  2  8
 ## [4,]  2  7 10  6  7  6  7  7  7 10  1
 ## [5,] 11  9 12 15 19  1 11 13 19  1 19
 ## [6,] 14 15 15 20 10 19 17 12 18 11  3
 ## [7,] 18  5  1 20  6 19  4 16 16 15 11
 ## [8,] 19  9 20 12 14  8 13  1 11 10  1
 ## [9,]  1 14  3  6  2  6  8 13 10 16 14

 ############# Instead of ##################
future.apply::future_apply(b, 1, min)
 ## [1] 4 5 1 1 1 3 1 1 1 ## is the smallest element in each row (row1 to row9), I want to print the `colname` of smallest element in each row of the matrix `b`. like this:
## [1] 2 4 2 12 11 12 4 12 1

Upvotes: 1

Views: 133

Answers (2)

akrun
akrun

Reputation: 886938

A base R option with apply

apply(b, 1, FUN = function(x) names(x)[which.min(x)])
#[1] "2"  "4"  "2"  "12" "7"  "12" "4"  "9"  "2" 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

You can use max.col negating the matrix b to get index of smallest value in each row. We can use this index to get corresponding column names.

colnames(b)[max.col(-b)]
#[1] "2"  "4"  "2"  "12" "11" "12" "4"  "12" "2" 

Upvotes: 1

Related Questions