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

R语言多众数处理:多众数场景下如何返回最后出现的众数

计算向量的统计众数时经常会出现多个众数的情况:

c(1, 1, 2, 2, 3, 4) # 众数同时为1和2

这类场景下如果需要在多个众数之间做选择,通常使用{collapse}包的fmode()函数,该函数通过ties参数提供了3种多众数处理方法:

ties
用于指定多个众数(即频率或权重和达到最大值的多个值)的平局处理规则的整数或字符串:

数值字符串值说明
1first取第一个出现的众数
2min取所有众数中的最小值
3max取所有众数中的最大值

fmode()使用示例

library(collapse)

my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2) # 此处共有4个众数:1、5、-6、2
fmode(my_vec, ties = "first")
#> [1] 1
fmode(my_vec, ties = "min")
#> [1] -6
fmode(my_vec, ties = "max")
#> [1] 5

问题描述

需要新增last处理规则,即存在多个众数时返回最后出现的众数,但fmode()目前不支持"last"参数值。以上述示例向量my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2)为例,期望调用自定义函数得到如下结果:

custom_mode_func(my_vec, method = "last")
## [1] 2

实现方案

依赖collapse包版本(保留原包高性能)

复用fmode()的现有能力,通过反转向量的方式快速实现last规则:

library(collapse)

custom_mode_func <- function(x, method = c("first", "min", "max", "last")) {
  method <- match.arg(method)
  if (method != "last") {
    return(fmode(x, ties = method))
  }
  # 反转向量后取第一个出现的众数,等价于原向量最后出现的众数
  return(fmode(rev(x), ties = "first"))
}

# 功能测试
my_vec <- c(1, 1, 3, 4, 5, 5, -6, -6, 2, 2)
custom_mode_func(my_vec, method = "last")
#> [1] 2

纯基础R版本(无第三方依赖)

如果不需要依赖外部包,也可以用基础R函数实现:

custom_mode_func_base <- function(x, method = c("first", "min", "max", "last")) {
  method <- match.arg(method)
  # 计算所有值的出现频率
  freq <- table(x)
  # 筛选出所有众数
  modes <- names(freq[freq == max(freq)])
  # 转换为和原向量一致的类型
  modes <- as(modes, class(x))
  # 按规则返回结果
  switch(method,
         first = modes[which.min(match(modes, x))],
         min = min(modes),
         max = max(modes),
         last = modes[which.max(match(modes, x))]
  )
}

# 功能测试
custom_mode_func_base(my_vec, method = "last")
#> [1] 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:06:02