r - 通过 grep 匹配后在列表中组合向量
问题描述
我有一个包含 1000 个较小向量的列表/向量(“x”),每个向量 1 行。这些子向量包括字符串和数字。其中一行包括嵌入在字符串中的“id: XXXX”变量。如果我只考虑前 2 个向量(即 x[[i]] 和 x[[i+1]]),我可以使用 R 中的以下代码来组合列表中的连续向量。
first_vec<-c("Page 1 of 1000", "Report of vectors within a list", "id: 1234 height: 164 cms", "health: good")
second_vec<-c("Page 2 of 1000", "Report of vectors within a list", "id: 1235 height: 180 cms", "health: moderate")
third_vec<-c("Page 3 of 1000", "Report of vectors within a list", "id: 1235 weight: 200 pounds", "health: moderate")
x<-list(first_vec, second_vec, third_vec)
X <- for (i in i:unique(length(x))) {
t1 <- unlist(stringr::str_extract_all(x[[i]][!is.na(sample)], "(id: [0-9]+)"))
t2 <- unlist(stringr::str_extract_all(x[[i + 1]][!is.na(sample)], "(id: [0-9]+)"))
if (t1 == t2) {
c(x[[i]], x[[i + 1]])
}
}
期望的结果是:
x<-list(first_vec, c(second_vec, third_vec)
当我只有两个子向量时,这对我有用。但是,我有一个包含 1000 个向量的列表。如何在列表 x 中的所有向量中循环上面的代码?
目前我收到以下错误消息: is.na(sample) 中的警告:
is.na() applied to non-(list or vector) of type 'closure'
Error in x[[i + 1]] : subscript out of bounds
我包括一个我正在应用代码的典型输入文件的示例。在下面的示例中,我想合并第 2 页和第 3 页,因为 id 匹配。
解决方案
在不知道您的数据的情况下。
你可以1)提取你的字符串,2)寻找这样的连续ID
library(stringr)
xx <- unique(x)
# loop over the xx vector and extract the ids
ids <- sapply(xx, function(s) str_extract(s, "\(id: [0-9]+\)"))
# filter for successive values
suc_ids <- ids[ids == lag(ids)]
推荐阅读
- sql - 计算两个时间记录之间的差异
- c# - 有什么方法可以使 ITicketStore 作用域?
- ascii - 反斜杠 n `\n` 真的是换行符,但被视为换行符吗?
- php - 我在打开时从错误中创建文件夹的模板
- apache-kafka - Kafka 代理从集群中移除且重新分配失败后降低主题复制因子
- postgresql - 为什么在同一个查询中,hash索引被忽略而使用btree索引
- javascript - How can I use form input values in my submission script?
- spring - 如何跳过@PostPersist 或@PostUpdate
- c - 使用 rewind() 返回错误,删除它可以让代码正常运行
- dialogflow-es - 如何在 Dialogflow CX 中使用预先录制的音频做出响应?