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

R语言展平嵌套列表并将父级列表名赋值给对应子组件

R嵌套列表展平并同步顶层分组名实现

问题场景

需要对两层嵌套的命名列表current_output做展平处理,规则如下:

  • 每个顶层分类的名称,需要赋值给该分类下包含的所有子组件
  • 展平后不打散子组件本身的向量结构,最终结构、命名完全匹配给定的expected输出

测试样例代码

A1 <- c(1:3)
A2 <- c(4:6)
A3 <- c(7:9)
B1 <- c(1:2)
B2 <- c(3:4)
B3 <- 1
C1 <- c(1:3)
C2 <- 1
C3 <- 1

l1 <- list(list(A1), list(A2), list(A3))
l2 <- list(list(B1),list(B2), list(1))
l3 <- list(list(C1), list(1), list(1))

current_output <- list(l1, l2, l3)
names(current_output) <- c("A", "B", "C")

expected <- list(A1, A2, A3, B1, B2, B3, C1, C2, C3)
names(expected) <- c(rep("A", 3), rep("B", 3), rep("C", 3))

实现方案

使用R基础函数即可完成,无需依赖第三方包:

# 核心处理逻辑
flattened <- unlist(
  lapply(names(current_output), \(nm) {
    # 提取当前分组下所有子项,解除二级嵌套
    items <- lapply(current_output[[nm]], `[[`, 1)
    # 为所有子项绑定当前顶层分组名
    setNames(items, rep(nm, length(items)))
  }),
  recursive = FALSE
)

# 校验结果一致性
identical(flattened, expected) # 返回TRUE即处理正确

注意事项:

  • unlist必须设置recursive = FALSE参数,否则会将子项中的原子向量继续拆解,导致最终结构不符合要求
  • 若使用4.1.0以下版本的R,将代码里的匿名函数写法\(nm)替换为function(nm)即可正常运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.06 16:15:42