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

如何根据分组向量定义的分组对列表元素进行分组?

根据分组向量合并列表元素的最简实现

问题场景

给定列表l和分组向量g:

l = list(3:4, 8:10, 7:8)
# [[1]]
# [1] 3 4
# 
# [[2]]
# [1]  8  9 10
# 
# [[3]]
# [1] 7 8

g = c("A", "B", "A")

需要按g的分组规则,将同组的列表元素合并,得到目标结果:

l_expected = list(c(3:4, 7:8), 8:10)
# [[1]]
# [1] 3 4 7 8
# 
# [[2]]
# [1]  8  9 10

最简解决方案

原生Base R实现(无需额外包)

用split按分组拆分列表,再用lapply对每个分组执行unlist合并元素,是最直接的写法:

result <- lapply(split(l, g), unlist)

输出结果会保留分组标签(如$A、$B),如果不需要标签仅保留列表结构,可添加unname():

result <- unname(lapply(split(l, g), unlist))

Tidyverse风格实现(purrr包)

如果你常用tidyverse生态,管道式写法更直观:

library(purrr)

result <- l %>% 
  split(g) %>% 
  map(unlist)

同样可以用unname()移除分组标签。


内容的提问来源于stack exchange,提问作者Maël

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:20:42