r语言 - 通过grep匹配后将列表内的向量组合



我有一个1000个小向量的列表/向量("x"),每个1行。这些子向量包括字符串和数字。其中一行包含"id: XXXX"变量,嵌入在字符串中。如果我只考虑前两个向量(即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(示例)中的警告: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)]

这是我对问题的理解和解决方案:您有一个单字符串向量列表,并希望将匹配模式的那些子字符串连接起来。如果这是正确的,那么这应该工作:

数据:

a <- "id: 20"
b <- "something id: 333some more"
c <- "some other stuff without id"
d <- "some stuff id: 346999 and more stuff"
x <- list(a,b,c,d)
unlist(stringr::str_extract(x, "id: [0-9]+"))
[1] "id: 20"     "id: 333"    NA           "id: 346999"

或(也许):

paste0(unlist(stringr::str_extract(x, "id: [0-9]+")), collapse = ", ")
"id: 20, id: 333, NA, id: 346999"

基于OP的更新数据:

paste0(unlist(stringr::str_extract_all(x, "Page \d+")), " ", unlist(stringr::str_extract_all(x, "id: [0-9]+")), collapse = ", ")
[1] "Page 1 id: 1234, Page 2 id: 1235, Page 3 id: 1235"

最新更新