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

在R语言中如何筛选矩阵,保留首次出现的唯一数值配对?

R语言简便实现矩阵配对筛选(移除含已出现数字的后续配对)

给定如下矩阵:

T_data = c(7,9,8,10,2,10,5,9,1,8,2,1,4,7,5,4,2,5)
T_new = matrix(T_data,ncol=2,byrow=TRUE)

需要按规则筛选:从矩阵顶部开始逐行检查,若当前配对中的任意数字已在之前保留的配对中出现过,则移除该行;仅保留所有数字均未出现过的配对,最终目标结果为:

[,1] [,2]
[1,]    7    9
[2,]    8   10
[3,]    2    1
[4,]    5    4

以下是无需手动循环的简便实现方法:


方法一:基础R的Reduce函数(无额外依赖)

利用Reduce逐行累积已出现的数字,同时判断是否保留当前行:

# 逐行处理,累积已出现的数字集合
seen_set <- Reduce(function(seen, current_row) {
  # 检查当前行是否有数字已出现过
  if (any(current_row %in% seen)) {
    seen  # 不保留该行,返回原已出现集合
  } else {
    c(seen, current_row)  # 保留该行,将数字加入已出现集合
  }
}, split(T_new, seq(nrow(T_new))), init = integer(0))

# 将累积的数字重新整理为两列矩阵
result <- matrix(seen_set, ncol = 2, byrow = TRUE)
print(result)

方法二:tidyverse工具链(适合熟悉dplyr/purrr的用户)

结合accumulate和filter实现筛选逻辑:

library(dplyr)
library(purrr)

result <- T_new %>%
  as_tibble(.name_repair = ~c("V1", "V2")) %>%
  mutate(row_num = row_number()) %>%
  # 累积每一步的已出现数字集合
  mutate(seen = accumulate(row_num, function(prev_seen, idx) {
    current_vals <- slice(cur_data(), idx) %>% select(V1, V2) %>% unlist()
    if (any(current_vals %in% prev_seen)) prev_seen else c(prev_seen, current_vals)
  }, .init = integer(0))[-1]) %>%
  # 筛选出两个数字都未在之前出现过的行
  filter(!V1 %in% seen & !V2 %in% seen) %>%
  select(V1, V2) %>%
  as.matrix()

print(result)

结果验证

两种方法运行后均会输出符合期望的矩阵:

[,1] [,2]
[1,]    7    9
[2,]    8   10
[3,]    2    1
[4,]    5    4

内容的提问来源于stack exchange,提问作者B. Jenkins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:45:26