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

在R中基于次级向量的缩进值,条件拼接向量中的标题字符串

解决方案

你可以通过维护一个当前层级的状态列表,逐行处理数据来生成所需的层级标题。核心思路是:

  • 对于每一行,先移除状态列表中所有缩进级别大于等于当前行的条目(因为这些条目不再是当前行的祖先层级)
  • 将当前行的缩进和内容加入状态列表
  • 按缩进级别排序后拼接成标题字符串

以下是具体的R代码实现:

# 原始数据
contents <- c('Heading 1', 'Subheading 1', 'Item 1', 'Item 2', 'Subheading 2', 'Item 1', 'Item 2', 'Heading 2','Subheading 1','Item 1','Item 2')
indents <- c(0,1,2,2,1,2,2,0,2,4,4)
df <- data.frame(indents,contents)

# 初始化变量
current_hierarchy <- list()
headings <- character(nrow(df))

# 逐行处理生成层级标题
for (i in 1:nrow(df)) {
  curr_indent <- df$indents[i]
  curr_content <- df$contents[i]
  
  # 移除所有缩进级别 >= 当前行的条目
  current_hierarchy <- current_hierarchy[as.numeric(names(current_hierarchy)) < curr_indent]
  
  # 添加当前行的内容到层级中
  current_hierarchy[[as.character(curr_indent)]] <- curr_content
  
  # 按缩进级别排序并拼接成标题
  sorted_indents <- sort(as.numeric(names(current_hierarchy)))
  sorted_content <- current_hierarchy[as.character(sorted_indents)]
  headings[i] <- paste(unlist(sorted_content), collapse = " | ")
}

# 将结果添加到原数据框
df$headings <- headings

# 查看结果
print(df)

运行这段代码后,df中的headings列就会生成你需要的层级标题格式。

代码逻辑说明

  1. 状态维护:current_hierarchy是一个以缩进级别为名称的列表,始终保存当前有效的祖先层级内容。
  2. 层级更新:遇到新行时,先清除所有比当前缩进级别高或相等的层级(因为这些是兄弟或子级,不再属于当前行的祖先),再加入当前行的内容。
  3. 排序拼接:按缩进级别从小到大排序后,用|拼接所有层级内容,得到最终的标题字符串。

这个方法能处理任意缩进级别的变化,包括非连续的缩进(比如示例中Heading 2下的缩进2、4),以及同一层级的切换(比如Subheading 1到Subheading 2的切换)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:37:33