You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求与max.col()功能相反的函数替代方案(类似min.col)

实现类似min.col()的几种简单方案

R里没有内置的min.col()函数,但可以用几种简单方式实现和max.col()完全对应的“找每行最小值所在列索引”的功能,下面给几个实用方案:

方案1:借助max.col()反向实现(最简洁高效)

因为最小值的等价逻辑是“取负后的最大值”,直接对矩阵取负后调用max.col(),就能得到原矩阵每行最小值的列索引,完美匹配max.col()的参数规则:

min_col <- function(mat, ties.method = "first") {
  max.col(-mat, ties.method = ties.method)
}

这个方法复用了R底层优化的max.col(),速度最快,参数和max.col()完全一致,支持ties.method参数(可选"first"/"last"处理重复最小值的情况)。

方案2:用apply()逐行计算(直观易懂)

如果觉得反向逻辑不好理解,用apply()逐行处理更直观,手动找出每行最小值的位置:

min_col <- function(mat, ties.method = "first") {
  apply(mat, 1, function(row) {
    min_val <- min(row)
    min_positions <- which(row == min_val)
    if (ties.method == "first") {
      min_positions[1]
    } else if (ties.method == "last") {
      min_positions[length(min_positions)]
    } else {
      stop("ties.method只能是'first'或'last'")
    }
  })
}

这个方法逻辑直白,适合新手理解,同样支持重复值的处理规则。

测试示例

用一个测试矩阵验证效果:

# 构造测试矩阵
test_matrix <- matrix(c(5, 2, 7, 1, 3, 2, 4, 0, 5), nrow = 3, byrow = TRUE)

# 调用函数找每行最小值的列索引
min_col(test_matrix)
# 输出:[1] 2 1 2

# 处理有重复最小值的情况
test_matrix_dup <- matrix(c(1, 3, 1, 2, 2, 4), nrow = 2, byrow = TRUE)
min_col(test_matrix_dup, ties.method = "last")
# 输出:[1] 3 2

内容的提问来源于stack exchange,提问作者lazlomeli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:31:07