打印R中每行最小元素的列名

  • 本文关键字:元素 打印 r matrix
  • 更新时间 :
  • 英文 :


我希望R打印包含矩阵每行中最小元素的列名。

最小再现性示例

################# 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

带有applybase R选项

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

您可以使用max.col否定矩阵b来获得每行中最小值的索引。我们可以使用这个索引来获取相应的列名。

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

最新更新