You need to enable JavaScript to run this app. R语言如何从dataframe指定列中识别出现频次最高的元素
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何从dataframe指定列中识别出现频次最高的元素

实现方案
  • 核心逻辑:将'Most frequent'列中逗号分隔的所有值拆分为独立条目,统计全量条目下的出现频次,取最高频值按指定格式输出
  • 可直接运行的完整R代码:
# 加载给定样本数据集
df <- structure(list(name = c("act1_25", "act1_26", "act1_27", "act1_28", 
    "act1_29", "act1_30", "act1_31", "act1_32", "act1_33", "act1_34", 
    "act1_35", "act1_36", "act1_37", "act1_38", "act1_39", "act1_40", 
    "act1_41", "act1_42", "act1_43", "act1_44", "act1_45", "act1_46", 
    "act1_47", "act1_48", "serial"), `Most frequent` = c("111,110,9120,310,3110,210,1110", 
    "210,3110,110,310,9120,9210,8210,3819,1110,111", "210,110,310,8210,3110,1110", 
    "210,9120,110,310,8210,1110,3819", "210,9120,310,110,1110,111", 
    "9120,110,1110,3830", "110,1110,3210,310", "210,110,1110,8210,310", 
    "1110,310,8210,110", "210,310,1110,8210,110", "310,1110,8210,210,110", 
    "3210,9120,1110,8210,110", "1110,210,310,110,3830", "1110,210,310,110,3210,3830", 
    "1110,8210,110,3830,3210", "1110,310,110,3210,5190", "1110,110,5190", 
    "1110,3210,3830,310,8210,110,5190", "1110,8210,310,210,1120,110", 
    "1110,8210,310", "1110,8210,310", "1110,8210,310,110", "1110,8210,310,110", 
    "210,1110,8210,5190,110", "27080618")), class = c("tbl_df", "tbl", 
    "data.frame"), row.names = c(NA, -25L))

# 拆分所有逗号分隔值,生成频次统计表
freq_count <- table(unlist(strsplit(df$`Most frequent`, split = ",")))
# 提取最高频值
highest_freq_val <- names(which.max(freq_count))
# 按要求格式输出结果
cat("Most frequent:", highest_freq_val, "\n")
代码运行后的实际输出
Most frequent: 1110

补充说明:如果存在多个值频次并列第一的情况,可将提取值的代码替换为names(freq_count)[freq_count == max(freq_count)],一次性获取所有并列最高频的条目。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.30 21:27:01