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

基于列分箱规则重排[6,2]矩阵行顺序的技术实现咨询

实现方案

以下是R语言环境下的可运行实现,支持自动分箱和手动自定义分箱两种模式:


方案1:自动分箱(无需手动定义分箱规则,默认等频分箱)

该方案不需要手动设置分箱断点,自动将第一列划分为指定数量的等频分箱,每个分箱样本量尽可能一致:

# 构造示例输入矩阵
mat <- matrix(
  c(968.3885, 438.3863,
    950.4227, 1862.5566,
    232.5512, 488.0292,
    245.5995, 1828.5346,
    445.5995, 1838.5346,
    412.4362, 446.0405),
  ncol = 2, byrow = TRUE,
  dimnames = list(paste0("[",1:6,",]"), c("[,1]", "[,2]"))
)

library(dplyr)
sorted_mat <- mat %>%
  as.data.frame() %>%
  # 参数n可修改为你需要的分箱数量,示例为3个分箱
  mutate(bin_col1 = ntile(desc(`[,1]`), n = 3)) %>%
  arrange(bin_col1, desc(`[,2]`)) %>%
  select(-bin_col1) %>%
  as.matrix()

方案2:手动定义分箱规则

如果需要自定义第一列的分箱区间,可以用cut函数手动设置断点:

# 自定义分箱断点,示例将第一列按数值划分为[0,300)、[300,600)、[600,1000]三个区间
breaks <- c(0, 300, 600, 1000)

sorted_mat_manual <- mat %>%
  as.data.frame() %>%
  mutate(bin_col1 = cut(`[,1]`, breaks = breaks, labels = FALSE, include.lowest = TRUE)) %>%
  arrange(desc(bin_col1), desc(`[,2]`)) %>%
  select(-bin_col1) %>%
  as.matrix()

纯base R实现(无需安装第三方包)

# 自动分3箱,breaks参数可修改为自定义断点数组
bin_col1 <- cut(mat[,1], breaks = 3, labels = FALSE)
# 按分箱降序、第二列降序排列行
sorted_mat_base <- mat[order(-bin_col1, -mat[,2]), ]

输出验证

运行后打印结果和预期完全一致:

print(sorted_mat)
#           [,1]      [,2]
# [1,]  950.4227 1862.5566
# [2,]  968.3885  438.3863
# [3,]  445.5995 1838.5346
# [4,]  412.4362  446.0405
# [5,]  245.5995 1828.5346
# [6,]  232.5512  488.0292

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 14:36:07