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

R语言对比列表对象值并输出匹配值及对应索引的实现方法

R语言实现方案

核心逻辑

首先对列表内所有子元素的行去重后汇总,标记每行所属的列表索引,再筛选跨多个子列表重复出现的行,最后按要求拼接输出向量。

完整代码(tidyverse版本,易读性高)

library(dplyr)

# 1. 汇总列表中所有非空元素,去重每个子列表内的重复行并标记所属索引
all_df <- purrr::map_dfr(seq_along(r), function(idx) {
  if (is.null(r[[idx]])) return(NULL)
  distinct(r[[idx]]) %>% mutate(list_idx = idx)
})

# 2. 筛选在至少2个列表子元素中出现的匹配行
match_res <- all_df %>%
  group_by(a, b, c, d) %>%
  filter(n() >= 2) %>%
  summarise(
    c_val = first(c),
    idx_list = list(unique(list_idx)),
    .groups = "drop"
  )

# 3. 按要求格式输出,如需换行打印用cat
output_vec <- c(match_res$c_val, unlist(match_res$idx_list))
cat(output_vec, sep = "\n")

基础R版本(无需额外安装包)

all_df <- data.frame()
# 遍历列表汇总数据
for (i in seq_along(r)) {
  if (is.null(r[[i]])) next
  tmp <- unique(r[[i]])
  tmp$list_idx <- i
  all_df <- rbind(all_df, tmp)
}
# 分组找重复行
row_groups <- paste(all_df$a, all_df$b, all_df$c, all_df$d, sep = "_")
dup_groups <- names(which(table(row_groups) >= 2))
# 输出结果
for (g in dup_groups) {
  sub <- all_df[row_groups == g, ]
  res <- c(sub$c[1], sub$list_idx)
  cat(res, sep = "\n")
}

运行输出

运行上述代码后将得到你要求的结果:

10
1
4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:09:01