如何转换str_locate_all输出为包含模式匹配所有位置的列表
转换
str_locate_all输出为全量匹配索引 你可以通过遍历str_locate_all()返回的列表结果,对每组匹配的起止位置生成连续整数序列,再拼接得到目标格式。
实现代码
首先加载依赖包,我们先构造和你示例完全一致的输入结构做测试:
library(stringr) # 模拟你的输入结构 match_loc <- list( matrix(c(4, 7), ncol = 2, dimnames = list(NULL, c("start", "end"))), matrix(c(8, 12, 30, 33), ncol = 2, byrow = TRUE, dimnames = list(NULL, c("start", "end"))) )
基础R版本转换逻辑,不需要额外安装包:
full_index <- lapply(match_loc, function(loc_matrix) { all_pos <- apply(loc_matrix, 1, function(row) { seq(from = row["start"], to = row["end"]) }) as.integer(unlist(all_pos)) })
运行后输出和你预期完全一致:
> full_index [[1]] [1] 4 5 6 7 [[2]] [1] 8 9 10 11 12 30 31 32 33
如果你日常使用tidyverse生态,也可以用更简洁的purrr写法:
library(purrr) full_index <- map(match_loc, ~as.integer(unlist(pmap(., seq))))
内容的提问来源于stack exchange,提问作者eglh
相关产品推荐
相关产品推荐

