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

在R语言中按层级拆分含|分隔符的表格文本数据

R语言按层级拆分文本分组

步骤1:构造输入数据

先把你的文本整理成R语言向量:

text_vec <- c(
  "x__lorem_01",
  "x__lorem|y__ipsum",
  "x__lorem.05",
  "x__lorem.05|y__ipsum|z__dolor02_sit",
  "x__lorem.05|y__ipsum|z__dolor02_sit|t__consectetur.adipiscing02",
  "x__lorem|y__ipsum004_01"
)

步骤2:计算每个文本的层级数

通过统计分隔符|的数量加1,得到每个字符串对应的层级数:

library(stringr)
# 统计|的数量,加1得到层级数
level_counts <- str_count(text_vec, fixed("|")) + 1

步骤3:按层级分组

用split()函数直接按层级数完成分组,再调整分组名称为你需要的格式:

# 按层级分组
grouped_text <- split(text_vec, level_counts)
# 重命名分组为"子集N"格式
names(grouped_text) <- paste0("子集", names(grouped_text))

最终分组结果

执行上述代码后,得到的分组如下:

子集1

  • x__lorem_01
  • x__lorem.05

子集2

  • x__lorem|y__ipsum
  • x__lorem|y__ipsum004_01

子集3

  • x__lorem.05|y__ipsum|z__dolor02_sit

子集4

  • x__lorem.05|y__ipsum|z__dolor02_sit|t__consectetur.adipiscing02

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 20:24:57